/**
 * 打印模板设计器
 */
layui.config({
    base: basePath,
    version: skyeyeVersion
}).extend({
    window: 'js/winui.window'
}).define(['window', 'jquery', 'winui', 'form', 'textool', 'colorpicker', 'fileUpload', 'slider'], function (exports) {
    winui.renderColor();
    var index = parent.layer.getFrameIndex(window.name);
    var layer = layui.layer;
    var form = layui.form;
    var $ = layui.jquery;
    var slider = layui.slider;
    var colorpicker = layui.colorpicker;

    /**
     * 配置项
     */
    var config = {
        // 默认元素配置
        defaultElementConfig: {
            width: 100,
            height: 40,
            rotate: 0,
            opacity: 100,
            fontSize: 14,
            align: 'left',
            borderStyle: 'none',
            borderWidth: 1,
            borderColor: '#d9d9d9',
            borderRadius: 0,
            borderRadiusUnit: 'px',
            transformOrigin: 'center',
            shadow: {
                enabled: false,
                x: 0,
                y: 0,
                blur: 5,
                color: 'rgba(0,0,0,0.3)'
            },
            animation: {
                type: 'none',
                duration: 500,
                delay: 0,
                direction: 'top'
            }
        },

        // 组件列表
        widgets: [
            {
                type: 'text',
                name: '文本',
                icon: 'layui-icon-font-bold',
                defaultConfig: {
                    width: 100,
                    height: 40,
                    content: '文本内容',
                    fontSize: 14,
                    align: 'left',
                    bold: false,
                    italic: false,
                    underline: false
                }
            },
            {
                type: 'image',
                name: '图片',
                icon: 'layui-icon-picture',
                defaultConfig: {
                    width: 120,
                    height: 120,
                    url: '',
                    value: '',
                    sourceType: 'upload',
                    fit: 'contain'
                }
            },
            {
                type: 'table',
                name: '表格',
                icon: 'layui-icon-table',
                defaultConfig: {
                    width: 300,
                    height: 150,
                    value: '',
                    rows: 3,
                    columns: [
                        { title: '列1', field: '', width: 100 },
                        { title: '列2', field: '', width: 100 },
                        { title: '列3', field: '', width: 100 }
                    ],
                    border: true,
                    showHeader: true,
                    headerBackground: '#f0f0f0',
                    headerColor: '#333'
                }
            },
            {
                type: 'barcode',
                name: '条码',
                icon: 'layui-icon-code-circle',
                defaultConfig: {
                    width: 200,
                    height: 80,
                    value: '12345678',
                    barcodeType: 'barcode',
                    format: 'CODE128',
                    showLabel: true,
                    fontSize: 12,
                    barWidth: 2,
                    textPosition: 'bottom',
                    errorLevel: 'M',
                    foreground: '#000000',
                    background: '#ffffff'
                }
            }
        ],

        // 标尺样式
        rulerStyle: {
            backgroundColor: '#f0f0f0',
            lineColor: '#d9d9d9',
            majorLineColor: '#a0a0a0',
            textColor: '#606060'
        },

        // 缩放配置
        scaleConfig: {
            defaultScale: 1,
            minScale: 0.2,
            maxScale: 2,
            scaleStep: 0.1
        },

        // 默认打印设置
        defaultPrintSettings: {
            paperSize: 'A4_PAGE',
            orientation: 'portrait',
            width: 210,
            height: 297,
            margin: {
                top: 10,
                right: 10,
                bottom: 10,
                left: 10
            }
        },

        // 纸张尺寸映射
        paperSizeMap: {
            A4_PAGE: { width: '210mm', height: '297mm' },
            A5_PAGE: { width: '148mm', height: '210mm' },
            A3_PAGE: { width: '297mm', height: '420mm' },
            LETTER_PAGE: { width: '215.9mm', height: '279.4mm' }
        },

        // 纸张尺寸选项
        paperSizeOptions: [
            { value: 'A3_PAGE', label: 'A3' },
            { value: 'A4_PAGE', label: 'A4' },
            { value: 'A5_PAGE', label: 'A5' },
            { value: 'LETTER_PAGE', label: '信纸' },
            { value: 'CUSTOM_PAGE', label: '自定义' }
        ]
    };

    /**
     * 打印模板设计器类
     */
    var PrintTemplateDesign = function (options) {
        this.options = $.extend({
            id: '',
            businessClassName: '',
            appId: ''
        }, options);

        // 状态数据
        this.templateName = '';
        this.elements = [];
        this.currentElement = null;
        this.selectedElements = [];
        this.businessFields = [];
        this.loading = false;
        this.scale = config.scaleConfig.defaultScale;

        // 初始化打印设置
        this.printSettings = $.extend({}, config.defaultPrintSettings);

        // 历史记录
        this.history = {
            past: [],
            future: []
        };

        // 标尺相关
        this.rulers = {
            horizontal: null,
            vertical: null
        };

        // 辅助线
        this.guides = {
            horizontal: [],
            vertical: []
        };

        // 对齐线
        this.alignLines = {
            vertical: [],
            horizontal: []
        };

        // 右键菜单
        this.contextMenu = {
            visible: false,
            x: 0,
            y: 0,
            element: null
        };

        // 变量搜索关键字
        this.variableSearchKeyword = '';

        // 当前变量选择器目标字段
        this.currentField = '';

        // 初始化
        this.init();
    };

    /**
     * 初始化方法
     */
    PrintTemplateDesign.prototype.init = function () {
        var self = this;

        // 初始化组件列表
        this.initComponentList();

        // 初始化事件监听
        this.initEventHandlers();

        // 初始化标尺
        this.initRulers();

        // 初始化打印设置
        this.initPrintSettings();

        // 获取业务字段
        this.fetchBusinessFields();

        // 加载模板数据
        this.loadTemplateData();

        // 初始化表单
        form.render();
    };

    /**
     * 初始化组件列表
     */
    PrintTemplateDesign.prototype.initComponentList = function () {
        var self = this;
        var html = '';

        $.each(config.widgets, function (index, widget) {
            html += '<div class="component-item" draggable="true" data-type="' + widget.type + '">' +
                '<div class="item-icon"><i class="layui-icon ' + widget.icon + '"></i></div>' +
                '<div class="item-name">' + widget.name + '</div>' +
                '</div>';
        });

        $('#componentList').html(html);
    };

    /**
     * 获取默认元素配置
     */
    PrintTemplateDesign.prototype.getDefaultConfig = function (type) {
        var widgetConfig = null;

        $.each(config.widgets, function (index, widget) {
            if (widget.type === type) {
                widgetConfig = widget.defaultConfig;
                return false;
            }
        });

        return $.extend({}, config.defaultElementConfig, widgetConfig);
    };

    /**
     * 初始化事件监听
     */
    PrintTemplateDesign.prototype.initEventHandlers = function () {
        var self = this;

        // 组件拖拽
        $(document).on('dragstart', '.component-item', function (e) {
            var type = $(this).data('type');
            e.originalEvent.dataTransfer.setData('widgetType', type);
        });

        // 放置元素
        $('#paper').on('dragover', function (e) {
            e.preventDefault();
        }).on('drop', function (e) {
            e.preventDefault();
            self.handleDrop(e);
        });

        // 打印设置按钮
        $('#printSettingsBtn').on('click', function () {
            self.showPrintSettingsModal();
        });

        // 撤销按钮
        $('#undoBtn').on('click', function () {
            self.handleUndo();
        });

        // 重做按钮
        $('#redoBtn').on('click', function () {
            self.handleRedo();
        });

        // 对齐按钮
        $('#alignLeftBtn').on('click', function () {
            self.alignElements('left');
        });

        $('#alignCenterBtn').on('click', function () {
            self.alignElements('center');
        });

        $('#alignRightBtn').on('click', function () {
            self.alignElements('right');
        });

        // 预览按钮
        $('#previewBtn').on('click', function () {
            self.handlePreview();
        });

        // 保存按钮
        $('#saveBtn').on('click', function () {
            self.handleSave(true);
        });

        // 组合按钮
        $('#groupBtn').on('click', function () {
            self.groupElements();
        });

        // 组内对齐按钮
        $('#alignLeftGroupBtn, #alignCenterGroupBtn, #alignRightGroupBtn').on('click', function () {
            var type = $(this).attr('id').replace('alignGroupBtn', '').toLowerCase();
            self.alignElements(type);
        });

        // 右键菜单项
        $('#copyMenuItem').on('click', function () {
            self.handleCopy();
        });

        $('#lockMenuItem').on('click', function () {
            self.handleLockElement();
        });

        $('#deleteMenuItem').on('click', function () {
            self.handleDelete();
        });

        $('#bringToFrontMenuItem').on('click', function () {
            self.bringToFront();
        });

        $('#sendToBackMenuItem').on('click', function () {
            self.sendToBack();
        });

        // 设计区域鼠标按下
        $('#designArea').on('mousedown', function (e) {
            if (e.target === this || e.target === $('#paper')[0]) {
                self.handleDesignAreaMouseDown(e);
            }
        });

        // 鼠标右键点击关闭菜单
        $(document).on('click', function () {
            self.closeContextMenu();
        });

        // 纸张大小选择变化
        form.on('select(paperSize)', function (data) {
            var value = data.value;
            if (value === 'CUSTOM_PAGE') {
                $('#customSizeFields').show();
            } else {
                $('#customSizeFields').hide();
            }
        });

        // 键盘事件
        $(document).on('keydown', function (e) {
            self.handleKeyDown(e);
        });

        // 滚轮缩放
        $('#designArea').on('wheel', function (e) {
            if (e.ctrlKey) {
                e.preventDefault();
                self.handleWheel(e);
            }
        });

        // 变量选择器按钮点击事件
        $(document).on('click', '.variable-selector-btn', function () {
            var target = $(this).data('target');
            self.showVariableSelector(target);
        });

        // 清空所有变量按钮点击事件
        $(document).on('click', '.clear-all', function () {
            if (self.currentElement && self.currentElement.type === 'text') {
                var element = self.currentElement;
                var content = element.content || '';
                // 替换所有变量
                element.content = content.replace(/\$\{[^}]+\}/g, '');
                // 更新属性面板
                self.updatePropertyPanel();
                // 重新渲染元素
                self.renderElements();
            }
        });

        // 清空表格数据源按钮点击事件
        $(document).on('click', '.clear-table-data-source', function () {
            if (self.currentElement && self.currentElement.type === 'table') {
                var element = self.currentElement;
                // 清空数据源变量
                element.value = '';
                // 清空所有列的字段
                if (element.columns) {
                    element.columns.forEach(function (col) {
                        col.field = '';
                    });
                }
                // 更新属性面板
                self.updatePropertyPanel();
                // 重新渲染元素
                self.renderElements();
            }
        });

        // 添加表格列按钮点击事件
        $(document).on('click', '.add-column', function () {
            if (self.currentElement && self.currentElement.type === 'table') {
                var element = self.currentElement;
                // 确保columns是一个数组
                if (!element.columns) {
                    element.columns = [];
                }
                // 添加新列
                element.columns.push({
                    key: Date.now(),
                    title: '新列',
                    field: '',
                    width: 100,
                    align: 'flex-start',
                    fontSize: 14,
                    wrap: true
                });
                // 更新属性面板
                self.updatePropertyPanel();
                // 重新渲染表单
                form.render();
            }
        });

        // 删除表格列按钮点击事件
        $(document).on('click', '.delete-column', function () {
            if (self.currentElement && self.currentElement.type === 'table') {
                var element = self.currentElement;
                var index = $(this).data('index');
                // 确保columns是一个数组且索引有效
                if (element.columns && index >= 0 && index < element.columns.length) {
                    element.columns.splice(index, 1);
                    // 如果删除后没有列了，添加一个默认列
                    if (element.columns.length === 0) {
                        element.columns.push({
                            key: Date.now(),
                            title: '列1',
                            field: '',
                            width: 100,
                            align: 'flex-start',
                            fontSize: 14,
                            wrap: true
                        });
                    }
                    // 更新属性面板
                    self.updatePropertyPanel();
                    // 重新渲染表单
                    form.render();
                }
            }
        });

        // 选择表格列字段按钮点击事件
        $(document).on('click', '.select-column-field', function () {
            if (self.currentElement && self.currentElement.type === 'table') {
                var columnIndex = $(this).data('index');
                if (!self.currentElement.value) {
                    layer.msg('请先选择数据源变量', { icon: 0 });
                    return;
                }

                self.showColumnFieldSelector(columnIndex);
            }
        });
    };

    /**
     * 初始化标尺
     */
    PrintTemplateDesign.prototype.initRulers = function () {
        var self = this;
        var hRuler = document.getElementById('hRuler');
        var vRuler = document.getElementById('vRuler');

        if (hRuler && vRuler) {
            self.rulers = {
                horizontal: hRuler.getContext('2d'),
                vertical: vRuler.getContext('2d')
            };
            self.updateRulers();
        }

        // 标尺滚动更新
        $('#designArea').on('scroll', function () {
            self.updateRulers();
        });
    };

    /**
     * 初始化打印设置
     */
    PrintTemplateDesign.prototype.initPrintSettings = function () {
        var html = '';

        // 渲染纸张大小选项
        $.each(config.paperSizeOptions, function (index, option) {
            html += '<option value="' + option.value + '">' + option.label + '</option>';
        });

        $('#paperSize').html(html);

        // 更新表单
        form.render('select');
    };

    /**
     * 加载模板数据
     */
    PrintTemplateDesign.prototype.loadTemplateData = function () {
        var self = this;
        self.loading = true;

        // 请求模板数据
        AjaxPostUtil.request({
            url: reqBasePath + 'queryPrintTemplateById',
            params: { id: self.options.id },
            type: 'json',
            method: 'POST',
            callback: function (json) {
                var templateData = json.bean;
                self.templateName = templateData.name;

                // 解析模板元素数据
                if (templateData.configContent) {
                    try {
                        var content = JSON.parse(templateData.configContent);
                        self.elements = content.elements || [];

                        // 渲染元素
                        self.renderElements();
                    } catch (e) {
                        self.elements = [];
                    }
                }

                // 设置打印设置
                var margin = templateData.margin ? JSON.parse(templateData.margin) : { top: 10, right: 10, bottom: 10, left: 10 };
                self.printSettings = {
                    paperSize: templateData.paperSize || 'A4_PAGE',
                    orientation: templateData.orientation || 'portrait',
                    width: templateData.width || 210,
                    height: templateData.height || 297,
                    margin: margin
                };

                // 更新打印设置表单
                self.updatePrintSettingsForm();

                // 更新纸张样式
                self.updatePaperStyle();
                self.loading = false;
            },
            async: false
        });
    };

    /**
     * 更新打印设置表单
     */
    PrintTemplateDesign.prototype.updatePrintSettingsForm = function () {
        var self = this;
        var settings = self.printSettings;

        // 设置纸张大小
        $('#paperSize').val(settings.paperSize);

        // 自定义尺寸显示控制
        if (settings.paperSize === 'CUSTOM_PAGE') {
            $('#customSizeFields').show();
            $('#paperWidth').val(settings.width);
            $('#paperHeight').val(settings.height);
        } else {
            $('#customSizeFields').hide();
        }

        // 设置方向
        $('#orientation').val(settings.orientation);

        // 设置边距
        $('#marginTop').val(settings.margin.top);
        $('#marginRight').val(settings.margin.right);
        $('#marginBottom').val(settings.margin.bottom);
        $('#marginLeft').val(settings.margin.left);

        // 更新表单
        form.render('select');
    };

    /**
     * 更新纸张样式
     */
    PrintTemplateDesign.prototype.updatePaperStyle = function () {
        var self = this;
        var settings = self.printSettings;

        // 将毫米转换为像素 (假设 96 DPI)
        var mmToPx = function (mm) {
            return Math.round(mm * 96 / 25.4);
        };

        // 根据纸张类型设置尺寸
        var paperWidth = 210;
        var paperHeight = 297;

        if (settings.paperSize === 'CUSTOM_PAGE') {
            paperWidth = settings.width;
            paperHeight = settings.height;
        } else if (config.paperSizeMap[settings.paperSize]) {
            var size = config.paperSizeMap[settings.paperSize];
            paperWidth = parseInt(size.width);
            paperHeight = parseInt(size.height);
        }

        // 如果是横向，交换宽高
        if (settings.orientation === 'landscape') {
            var temp = paperWidth;
            paperWidth = paperHeight;
            paperHeight = temp;
        }

        // 应用样式
        $('#paper').css({
            width: mmToPx(paperWidth) + 'px',
            height: mmToPx(paperHeight) + 'px',
            padding: mmToPx(settings.margin.top) + 'px ' +
                mmToPx(settings.margin.right) + 'px ' +
                mmToPx(settings.margin.bottom) + 'px ' +
                mmToPx(settings.margin.left) + 'px'
        });

        // 更新缩放显示
        $('#scaleDisplay').text(Math.round(self.scale * 100) + '%');

        // 更新标尺
        self.updateRulers();
    };

    /**
     * 渲染元素
     */
    PrintTemplateDesign.prototype.renderElements = function () {
        var self = this;
        var elementsContainer = $('#elements');
        elementsContainer.empty();

        $.each(self.elements, function (index, element) {
            var elementHtml = self.createElementHtml(element);
            elementsContainer.append(elementHtml);

            // 添加元素事件监听
            self.addElementEventListeners(element);
        });
    };

    /**
     * 创建元素HTML
     */
    PrintTemplateDesign.prototype.createElementHtml = function (element) {
        var self = this;
        var style = self.getElementStyle(element);
        var styleStr = '';

        // 转换样式对象为字符串
        $.each(style, function (key, value) {
            if (value !== undefined && value !== null) {
                // 转换驼峰命名为连字符命名
                var cssKey = key.replace(/([A-Z])/g, '-$1').toLowerCase();
                styleStr += cssKey + ':' + value + ';';
            }
        });

        var classList = ['design-element'];
        if (self.currentElement && self.currentElement.id === element.id) {
            classList.push('active');
        }
        if (element.type === 'group') {
            classList.push('group');
        }
        if (element.locked) {
            classList.push('locked');
        }
        if (element.type === 'text' && element.animation && element.animation.type !== 'none') {
            classList.push('preview-mode');
        }

        var html = '<div class="' + classList.join(' ') + '" data-id="' + element.id + '" style="' + styleStr + '">';

        // 根据元素类型渲染内容
        switch (element.type) {
            case 'text':
                var contentStyle = self.getContentStyle(element);
                var contentStyleStr = '';

                $.each(contentStyle, function (key, value) {
                    if (value !== undefined && value !== null) {
                        var cssKey = key.replace(/([A-Z])/g, '-$1').toLowerCase();
                        contentStyleStr += cssKey + ':' + value + ';';
                    }
                });

                html += '<div style="' + contentStyleStr + '">' + (element.content || '') + '</div>';
                break;

            case 'image':
                var imageUrl = '';
                // 根据图片来源确定显示的图片
                if (element.sourceType === 'upload') {
                    imageUrl = element.url || '';
                } else {
                    // 变量模式下可以显示变量值或占位图
                    imageUrl = element.value ? element.value : '';
                }

                if (imageUrl) {
                    html += '<img src="' + imageUrl + '" style="width:100%;height:100%;object-fit:' + (element.fit || 'contain') + ';">';
                } else {
                    // 没有值时显示占位符
                    html += '<div style="width:100%;height:100%;display:flex;justify-content:center;align-items:center;border:1px dashed #ccc;background-color:#f9f9f9;flex-direction:column;">' +
                        '<i class="layui-icon layui-icon-picture" style="font-size:24px;color:#aaa;margin-bottom:5px;"></i>' +
                        '<div style="color:#999;font-size:12px;">请在右侧设置图片</div>' +
                        '</div>';
                }
                break;

            case 'table':
                html += self.renderTable(element);
                break;

            case 'barcode':
                // 创建一个默认值，以确保条码不会为空
                var value = element.value || '12345678';
                var barcodeType = element.barcodeType || 'barcode';
                var format = element.format || 'CODE128';
                var foreground = element.foreground || '#000000';
                var background = element.background || '#ffffff';

                if (barcodeType === 'barcode') {
                    html += '<div class="barcode-container" style="width:100%;height:100%;display:flex;justify-content:center;align-items:center;" ' +
                        'data-value="' + value + '" ' +
                        'data-format="' + format + '" ' +
                        'data-show-label="' + (element.showLabel ? 'true' : 'false') + '" ' +
                        'data-text-position="' + (element.textPosition || 'bottom') + '" ' +
                        'data-bar-width="' + (element.barWidth || 2) + '" ' +
                        'data-font-size="' + (element.fontSize || 12) + '" ' +
                        'data-foreground="' + foreground + '" ' +
                        'data-background="' + background + '"' +
                        '>';

                    // 添加一个临时条码图像，让用户能看到
                    html += '<svg width="90%" height="90%" viewBox="0 0 100 50">' +
                        '<rect x="10" y="10" width="10" height="30" fill="' + foreground + '"></rect>' +
                        '<rect x="25" y="10" width="5" height="30" fill="' + foreground + '"></rect>' +
                        '<rect x="35" y="10" width="10" height="30" fill="' + foreground + '"></rect>' +
                        '<rect x="50" y="10" width="5" height="30" fill="' + foreground + '"></rect>' +
                        '<rect x="60" y="10" width="5" height="30" fill="' + foreground + '"></rect>' +
                        '<rect x="70" y="10" width="10" height="30" fill="' + foreground + '"></rect>' +
                        '<rect x="85" y="10" width="5" height="30" fill="' + foreground + '"></rect>';

                    if (element.showLabel) {
                        // 根据文本位置属性调整 y 坐标
                        var textY = element.textPosition === 'top' ? 10 : 45;
                        // top 位置时文本在条码上方，需要将文本的垂直位置调整为在条码上方
                        if (element.textPosition === 'top') {
                            html += '<text x="50" y="' + textY + '" text-anchor="middle" font-size="' + (element.fontSize || 12) + '" fill="' + foreground + '">' + value + '</text>';
                        } else {
                            html += '<text x="50" y="45" text-anchor="middle" font-size="' + (element.fontSize || 12) + '" fill="' + foreground + '">' + value + '</text>';
                        }
                    }

                    html += '</svg></div>';
                } else {
                    html += '<div class="qrcode-container" style="width:100%;height:100%;display:flex;justify-content:center;align-items:center;" ' +
                        'data-value="' + value + '" ' +
                        'data-error-level="' + (element.errorLevel || 'M') + '" ' +
                        'data-foreground="' + foreground + '" ' +
                        'data-background="' + background + '"' +
                        '>';

                    // 添加一个临时QR码图像
                    var size = Math.min(element.width, element.height) * 0.8;
                    html += '<svg width="' + size + '" height="' + size + '" viewBox="0 0 100 100">' +
                        '<rect x="10" y="10" width="80" height="80" fill="' + background + '" stroke="' + foreground + '" stroke-width="2"></rect>' +
                        '<rect x="20" y="20" width="20" height="20" fill="' + foreground + '"></rect>' +
                        '<rect x="60" y="20" width="20" height="20" fill="' + foreground + '"></rect>' +
                        '<rect x="20" y="60" width="20" height="20" fill="' + foreground + '"></rect>' +
                        '<rect x="45" y="45" width="10" height="10" fill="' + foreground + '"></rect>' +
                        '</svg>';

                    html += '</div>';
                }
                break;
        }

        // 如果是当前选中元素，添加控制手柄
        if (self.currentElement && self.currentElement.id === element.id) {
            html += '<div class="resize-handles">' +
                '<div class="handle handle-se"></div>' +
                '</div>' +
                '<div class="rotate-handle">' +
                '<i class="layui-icon layui-icon-refresh"></i>' +
                '</div>';
        }

        html += '</div>';

        return html;
    };

    /**
     * 获取元素样式
     */
    PrintTemplateDesign.prototype.getElementStyle = function (element) {
        // 确保所有值都是有效数值
        var x = parseInt(element.x) || 0;
        var y = parseInt(element.y) || 0;
        var width = parseInt(element.width) || 100;
        var height = parseInt(element.height) || 40;

        var style = {
            position: 'absolute',
            left: x + 'px',
            top: y + 'px',
            width: width + 'px',
            height: height + 'px',
            transformOrigin: element.transformOrigin || 'center',
            transition: 'transform 0.3s ease',
            backgroundColor: element.backgroundColor || 'transparent'
        };

        // 处理旋转和缩放
        var transforms = [];
        if (element.rotate) {
            transforms.push('rotate(' + element.rotate + 'deg)');
        }
        if (element.scale) {
            transforms.push('scale(' + element.scale + ')');
        }
        if (transforms.length > 0) {
            style.transform = transforms.join(' ');
        }

        // 处理透明度
        if (element.opacity) {
            style.opacity = element.opacity / 100;
        }

        // 处理圆角
        if (element.borderRadius) {
            style.borderRadius = element.borderRadius + (element.borderRadiusUnit || 'px');
        }

        // 处理边框样式
        if (element.borderStyle && element.borderStyle !== 'none') {
            style.borderStyle = element.borderStyle;
            style.borderWidth = (element.borderWidth || 1) + 'px';
            style.borderColor = element.borderColor || '#d9d9d9';
        } else {
            // 如果是文本或图片元素，且没有设置边框，显示虚线边框
            if (element.type === 'text' || element.type === 'image') {
                style.border = '1px dashed #ddd';
            }
        }

        // 处理阴影
        if (element.shadow && element.shadow.enabled) {
            // 确保所有阴影属性都有有效值
            var shadowX = element.shadow.x || 0;
            var shadowY = element.shadow.y || 0;
            var shadowBlur = element.shadow.blur || 5;
            var shadowColor = element.shadow.color || 'rgba(0,0,0,0.3)';

            style.boxShadow = shadowX + 'px ' +
                shadowY + 'px ' +
                shadowBlur + 'px ' +
                shadowColor;
        }

        return style;
    };

    /**
     * 获取内容样式
     */
    PrintTemplateDesign.prototype.getContentStyle = function (element) {
        // 根据对齐方式设置justifyContent
        var justifyContent = 'flex-start';
        if (element.align === 'center') {
            justifyContent = 'center';
        } else if (element.align === 'flex-end') {
            justifyContent = 'flex-end';
        }

        return {
            fontSize: (element.fontSize || 14) + 'px',
            color: element.color || '#000000',
            fontWeight: element.bold ? 'bold' : 'normal',
            fontStyle: element.italic ? 'italic' : 'normal',
            textDecoration: element.underline ? 'underline' : 'none',
            width: '100%',
            height: '100%',
            display: 'flex',
            alignItems: 'center',
            justifyContent: justifyContent,
            padding: '4px'
        };
    };

    /**
     * 渲染表格
     */
    PrintTemplateDesign.prototype.renderTable = function (element) {
        // 确保列配置存在
        if (!element.columns || !Array.isArray(element.columns) || element.columns.length === 0) {
            element.columns = [
                { key: Date.now(), title: '列1', field: '', width: 100, align: 'flex-start', fontSize: 14, wrap: true }
            ];
        }

        var rowHeight = element.rowHeight || 40;
        var html = '<table style="width:100%;border-collapse:collapse;">';

        // 表头
        if (element.showHeader !== false) {
            html += '<thead><tr style="background-color:' + (element.headerBackground || '#f0f0f0') + ';color:' + (element.headerColor || '#333') + ';height:' + rowHeight + 'px;">';

            $.each(element.columns, function (index, column) {
                var align = column.align || 'flex-start';
                var textAlign = 'left';
                if (align === 'center') textAlign = 'center';
                if (align === 'flex-end') textAlign = 'right';

                html += '<th style="width:' + (column.width || 100) + 'px;padding:4px;text-align:' + textAlign + ';';
                html += 'border:1px solid #ddd;';
                if (column.fontSize) {
                    html += 'font-size:' + column.fontSize + 'px;';
                }
                if (column.wrap) {
                    html += 'word-break:break-word;white-space:normal;';
                }
                html += '">' + (column.title || '') + '</th>';
            });

            html += '</tr></thead>';
        }

        // 表身
        html += '<tbody>';
        // 显示3行作为预览
        var previewRows = 3;
        for (var i = 0; i < previewRows; i++) {
            // 如果启用斑马纹，设置背景色
            var rowStyle = '';
            if (element.zebra && i % 2 === 1) {
                rowStyle = 'background-color:#f9f9f9;';
            }

            html += '<tr style="height:' + rowHeight + 'px;' + rowStyle + '">';

            $.each(element.columns, function (index, column) {
                var align = column.align || 'flex-start';
                var textAlign = 'left';
                if (align === 'center') textAlign = 'center';
                if (align === 'flex-end') textAlign = 'right';

                html += '<td style="padding:4px;text-align:' + textAlign + ';';
                html += 'border:1px solid #ddd;';
                if (column.fontSize) {
                    html += 'font-size:' + column.fontSize + 'px;';
                }
                if (column.wrap) {
                    html += 'word-break:break-word;white-space:normal;';
                }

                // 为变量字段显示字段名称
                var cellContent = '';
                if (column.field && column.field.match(/\$\{[^}]+\}/)) {
                    var fieldKey = column.field.replace(/\$\{|\}/g, '');
                    cellContent = fieldKey;
                }

                html += '">' + cellContent + '</td>';
            });

            html += '</tr>';
        }
        html += '</tbody></table>';

        return html;
    };

    /**
     * 添加元素事件监听
     */
    PrintTemplateDesign.prototype.addElementEventListeners = function (element) {
        var self = this;
        var $element = $('.design-element[data-id="' + element.id + '"]');

        // 鼠标按下
        $element.on('mousedown', function (e) {
            if (e.target.classList.contains('handle')) return;
            if (element.locked) return;

            self.handleElementMouseDown(e, element);
        });

        // 右键菜单
        $element.on('contextmenu', function (e) {
            e.preventDefault();
            self.handleContextMenu(e, element);
        });

        // 缩放手柄
        $element.find('.handle-se').on('mousedown', function (e) {
            e.stopPropagation();
            self.handleResizeMouseDown(e, element);
        });

        // 旋转手柄
        $element.find('.rotate-handle').on('mousedown', function (e) {
            e.stopPropagation();
            self.handleRotateMouseDown(e, element);
        });
    };

    /**
     * 更新属性面板
     */
    PrintTemplateDesign.prototype.updatePropertyPanel = function () {
        var self = this;
        var element = self.currentElement;

        if (!element) {
            $('#propertyPanel').empty();
            return;
        }

        var html = '<form class="layui-form" lay-filter="elementPropertyForm">';

        // 根据元素类型添加特定属性设置
        switch (element.type) {
            case 'text':
                html += self.renderTextSettings(element);
                break;

            case 'image':
                html += self.renderImageSettings(element);
                break;

            case 'table':
                html += self.renderTableSettings(element);
                break;

            case 'barcode':
                html += self.renderBarcodeSettings(element);
                break;
        }

        // 添加通用样式设置
        html += self.renderCommonStyleSettings(element);

        html += '</form>';

        $('#propertyPanel').html(html);

        // 渲染表单
        form.render(null, 'elementPropertyForm');

        // 初始化颜色选择器
        self.initColorPickers(element);

        // 初始化上传组件
        if (element.type === 'image' && element.sourceType === 'upload') {
            $("#imageUploader").upload({
                "action": reqBasePath + "common003",
                "data-num": "1",
                "data-type": imageType,
                "uploadType": 42,
                "data-value": element.url || '',
                "function": function (_this, data) {
                    // 更新图片URL
                    if (data && data.length > 0) {
                        element.url = data[0].src;
                        self.renderElements();
                    }
                }
            });
        }

        // 监听表单变化
        form.on('submit(elementPropertySubmit)', function (data) {
            $.extend(element, data.field);
            self.renderElements();
            return false;
        });

        // 监听单选框和下拉框变化
        form.on('select', function (data) {
            var name = $(data.elem).attr('name');
            element[name] = data.value;

            // 处理特殊情况：图片来源类型和条码类型切换
            if (name === 'sourceType' || name === 'barcodeType') {
                // 重新生成属性面板
                self.updatePropertyPanel();
            }

            // 处理边框样式变化
            if (name === 'borderStyle') {
                if (data.value === 'none') {
                    $('#borderSettings').hide();
                } else {
                    $('#borderSettings').show();
                }
            }

            self.renderElements();
        });

        form.on('radio', function (data) {
            var name = $(data.elem).attr('name');
            element[name] = data.value;
            self.renderElements();
        });

        form.on('switch', function (data) {
            var name = $(data.elem).attr('name');

            // 处理表格列属性
            if (name && name.indexOf('column') === 0) {
                self.handleColumnPropertyChange(name, data.elem.checked);
                return;
            }

            // 处理阴影启用开关
            if (name === 'shadowEnabled') {
                if (!element.shadow) {
                    element.shadow = {
                        enabled: data.elem.checked,
                        x: 0,
                        y: 0,
                        blur: 5,
                        color: 'rgba(0,0,0,0.3)'
                    };
                } else {
                    element.shadow.enabled = data.elem.checked;
                }

                // 显示或隐藏阴影设置区域
                if (data.elem.checked) {
                    $('#shadowSettings').show();
                } else {
                    $('#shadowSettings').hide();
                }

                self.renderElements();
                return;
            }

            element[name] = data.elem.checked;

            // 条码文本显示切换
            if (name === 'showLabel' && element.type === 'barcode') {
                // 不再完全刷新面板，而是动态启用/禁用文本位置设置
                if (data.elem.checked) {
                    $('#textPositionSettings').css('opacity', '1');
                    $('#textPositionSettings select').prop('disabled', false);
                } else {
                    $('#textPositionSettings').css('opacity', '0.6');
                    $('#textPositionSettings select').prop('disabled', true);
                }
            }

            self.renderElements();
        });

        // 监听复选框变化
        form.on('checkbox', function (data) {
            var name = $(data.elem).attr('name');

            // 处理表格列属性
            if (name && name.indexOf('column') === 0) {
                self.handleColumnPropertyChange(name, data.elem.checked);
                return;
            }

            element[name] = data.elem.checked;
            self.renderElements();
        });

        // 监听文本输入框变化
        $('#propertyPanel').on('input', 'input[type="text"], textarea', function () {
            var name = $(this).attr('name');

            // 处理表格列属性
            if (name && name.indexOf('column') === 0) {
                self.handleColumnPropertyChange(name, $(this).val());
                return;
            }

            element[name] = $(this).val();
            self.renderElements();
        });

        // 监听数字输入框变化
        $('#propertyPanel').on('input', 'input[type="number"]', function () {
            var name = $(this).attr('name');

            // 处理表格列属性
            if (name && name.indexOf('column') === 0) {
                self.handleColumnPropertyChange(name, parseFloat($(this).val()));
                return;
            }

            // 处理阴影属性
            if (name === 'shadowX' || name === 'shadowY' || name === 'shadowBlur') {
                if (!element.shadow) {
                    element.shadow = {
                        enabled: true,
                        x: 0,
                        y: 0,
                        blur: 5,
                        color: 'rgba(0,0,0,0.3)'
                    };
                }

                switch (name) {
                    case 'shadowX':
                        element.shadow.x = parseFloat($(this).val());
                        break;
                    case 'shadowY':
                        element.shadow.y = parseFloat($(this).val());
                        break;
                    case 'shadowBlur':
                        element.shadow.blur = parseFloat($(this).val());
                        break;
                }

                self.renderElements();
                return;
            }

            element[name] = parseFloat($(this).val());
            self.renderElements();
        });

        // 监听选择框变化
        form.on('select', function (data) {
            var name = $(data.elem).attr('name');

            // 处理表格列属性
            if (name && name.indexOf('column') === 0) {
                self.handleColumnPropertyChange(name, data.value);
                return;
            }

            element[name] = data.value;
            self.renderElements();
        });
    };

    /**
     * 渲染文本设置
     */
    PrintTemplateDesign.prototype.renderTextSettings = function (element) {
        // 确保属性存在
        if (!element.sourceType) {
            element.sourceType = 'text';
        }

        // 文本内容与变量选择器
        var html = '<div class="layui-form-item">' +
            '<label class="layui-form-label">内容</label>' +
            '<div class="layui-input-block">' +
            '<div class="content-editor">' +
            '<div class="editor-toolbar" style="display:flex;justify-content:space-between;margin-bottom:8px;">' +
            '<div class="toolbar-left">' +
            '<button type="button" class="layui-btn layui-btn-primary layui-btn-sm variable-selector-btn" data-target="content">' +
            '<i class="layui-icon layui-icon-template"></i> 插入变量' +
            '</button>' +
            '</div>' +
            '</div>' +
            '<textarea name="content" class="layui-textarea" style="min-height:100px;">' + (element.content || '') + '</textarea>' +
            '</div>' +
            '</div>' +
            '</div>';

        // 抽取变量预览
        if (element.content && element.content.match(/\$\{[^}]+\}/)) {
            html += '<div class="layui-form-item">' +
                '<div class="layui-input-block">' +
                '<div class="variable-preview" style="border:1px solid #e6e6e6;padding:10px;border-radius:2px;margin-top:8px;">' +
                '<div class="preview-header" style="display:flex;justify-content:space-between;margin-bottom:8px;">' +
                '<div class="preview-title">已插入变量</div>' +
                '<a class="clear-all" style="color:#1890ff;cursor:pointer;">清空所有</a>' +
                '</div>' +
                '<div class="variable-tags" style="display:flex;flex-wrap:wrap;">';

            // 提取变量
            var matches = element.content.match(/\$\{[^}]+\}/g) || [];
            matches.forEach(function (variable) {
                var key = variable.replace(/\$\{|\}/g, '');
                html += '<div class="variable-tag" style="background:#f0f0f0;padding:2px 8px;border-radius:2px;margin-right:8px;margin-bottom:8px;">' +
                    '<span class="tag-name">' + key + '</span>' +
                    '</div>';
            });

            html += '</div></div></div></div>';
        }

        // 字体大小设置
        html += '<div class="layui-form-item">' +
            '<label class="layui-form-label">字体大小</label>' +
            '<div class="layui-input-block">' +
            '<input type="number" name="fontSize" value="' + (element.fontSize || 14) + '" min="12" max="72" class="layui-input">' +
            '</div>' +
            '</div>';

        // 对齐方式 - 调整为Vue版本的值
        html += '<div class="layui-form-item">' +
            '<label class="layui-form-label">对齐方式</label>' +
            '<div class="layui-input-block">' +
            '<select name="align">' +
            '<option value="flex-start" ' + (element.align === 'flex-start' ? 'selected' : '') + '>左对齐</option>' +
            '<option value="center" ' + (element.align === 'center' ? 'selected' : '') + '>居中</option>' +
            '<option value="flex-end" ' + (element.align === 'flex-end' ? 'selected' : '') + '>右对齐</option>' +
            '</select>' +
            '</div>' +
            '</div>';

        // 文本样式
        html += '<div class="layui-form-item">' +
            '<label class="layui-form-label">字体样式</label>' +
            '<div class="layui-input-block">' +
            '<input type="checkbox" name="bold" title="粗体" lay-skin="primary" ' + (element.bold ? 'checked' : '') + '>' +
            '<input type="checkbox" name="italic" title="斜体" lay-skin="primary" ' + (element.italic ? 'checked' : '') + '>' +
            '<input type="checkbox" name="underline" title="下划线" lay-skin="primary" ' + (element.underline ? 'checked' : '') + '>' +
            '</div>' +
            '</div>';

        // 文字颜色
        html += '<div class="layui-form-item">' +
            '<label class="layui-form-label">文字颜色</label>' +
            '<div class="layui-input-block">' +
            '<div id="textColorPicker"></div>' +
            '<input type="hidden" id="textColorInput" name="color" value="' + (element.color || '#000000') + '">' +
            '</div>' +
            '</div>';

        return html;
    };

    /**
     * 渲染图片设置
     */
    PrintTemplateDesign.prototype.renderImageSettings = function (element) {
        // 确保sourceType属性存在
        if (!element.sourceType) {
            element.sourceType = 'upload';
        }

        var html = '<div class="layui-form-item">' +
            '<label class="layui-form-label">图片来源</label>' +
            '<div class="layui-input-block">' +
            '<select name="sourceType" lay-filter="sourceType">' +
            '<option value="upload" ' + (element.sourceType === 'upload' ? 'selected' : '') + '>上传图片</option>' +
            '<option value="variable" ' + (element.sourceType === 'variable' ? 'selected' : '') + '>变量图片</option>' +
            '</select>' +
            '</div>' +
            '</div>';

        // 根据图片来源类型显示不同的设置项
        if (element.sourceType === 'upload') {
            html += '<div class="layui-form-item">' +
                '<label class="layui-form-label">上传图片</label>' +
                '<div class="layui-input-block">' +
                '<div class="upload" id="imageUploader"></div>' +
                '</div>' +
                '</div>';
        } else {
            html += '<div class="layui-form-item">' +
                '<label class="layui-form-label">选择变量</label>' +
                '<div class="layui-input-block">' +
                '<div class="layui-input-group">' +
                '<input type="text" name="value" value="' + (element.value || '') + '" class="layui-input" readonly>' +
                '<div class="layui-input-suffix">' +
                '<button type="button" class="layui-btn layui-btn-primary layui-btn-sm variable-selector-btn" data-target="value">' +
                '<i class="layui-icon layui-icon-template"></i> 选择变量' +
                '</button>' +
                '</div>' +
                '</div>' +
                '</div>' +
                '</div>';
        }

        // 适应方式
        html += '<div class="layui-form-item">' +
            '<label class="layui-form-label">填充方式</label>' +
            '<div class="layui-input-block">' +
            '<select name="fit">' +
            '<option value="contain" ' + (element.fit === 'contain' ? 'selected' : '') + '>适应</option>' +
            '<option value="cover" ' + (element.fit === 'cover' ? 'selected' : '') + '>覆盖</option>' +
            '<option value="fill" ' + (element.fit === 'fill' ? 'selected' : '') + '>拉伸</option>' +
            '</select>' +
            '</div>' +
            '</div>';

        // 图片预览
        html += '<div class="layui-form-item">' +
            '<label class="layui-form-label">预览</label>' +
            '<div class="layui-input-block">';

        var imageUrl = '';
        // 根据图片来源确定预览图片
        if (element.sourceType === 'upload') {
            imageUrl = element.url || '';
        } else {
            // 变量模式下可以显示变量名或默认图片
            imageUrl = element.value ? element.value : '';
        }

        if (imageUrl) {
            html += '<div style="width:100%;height:150px;border:1px solid #d9d9d9;border-radius:2px;overflow:hidden;display:flex;align-items:center;justify-content:center;background:#fafafa;">' +
                '<img src="' + imageUrl + '" style="max-width:100%;max-height:100%;object-fit:' + (element.fit || 'contain') + ';">' +
                '</div>';
        } else {
            html += '<div style="width:100%;height:150px;border:1px dashed #d9d9d9;border-radius:2px;display:flex;flex-direction:column;align-items:center;justify-content:center;background:#fafafa;color:#999;">' +
                '<i class="layui-icon layui-icon-picture" style="font-size:32px;margin-bottom:8px;"></i>' +
                '<span>暂无图片</span>' +
                '</div>';
        }

        html += '</div></div>';

        return html;
    };

    /**
     * 渲染表格设置
     */
    PrintTemplateDesign.prototype.renderTableSettings = function (element) {
        // 初始化列配置，确保它是一个数组
        if (!element.columns || !Array.isArray(element.columns)) {
            element.columns = [
                { key: Date.now(), title: '列1', field: '', width: 100, align: 'flex-start', fontSize: 14, wrap: true },
                { key: Date.now() + 1, title: '列2', field: '', width: 100, align: 'flex-start', fontSize: 14, wrap: true }
            ];
        }

        // 数据源设置
        var html = '<div class="layui-form-item">' +
            '<label class="layui-form-label">数据源</label>' +
            '<div class="layui-input-block">' +
            '<div class="source-input-group">' +
            '<button type="button" class="layui-btn layui-btn-primary layui-btn-sm variable-selector-btn" data-target="value">' +
            '<i class="layui-icon layui-icon-template"></i> 选择变量' +
            '</button>';

        // 已选变量预览
        if (element.value) {
            var varKey = element.value.replace(/\$\{|\}/g, '');
            var varName = varKey;

            // 查找匹配的业务字段名称
            var field = this.businessFields.find(function (f) { return f.attrKey === varKey; });
            if (field) {
                varName = field.name;
            }

            html += '<div class="variable-preview" style="margin-top:8px;border:1px solid #e6e6e6;padding:10px;border-radius:2px;">' +
                '<div class="preview-header" style="display:flex;justify-content:space-between;margin-bottom:8px;">' +
                '<div class="preview-title">已选变量</div>' +
                '<a class="clear-table-data-source" style="color:#1890ff;cursor:pointer;">清空</a>' +
                '</div>' +
                '<div class="variable-tag" style="background:#f0f0f0;padding:2px 8px;border-radius:2px;display:inline-block;">' +
                '<span class="tag-name">' + varName + '</span>' +
                '</div>' +
                '</div>';
        }

        html += '</div>' +
            '</div>' +
            '</div>';

        // 列配置
        html += '<div class="layui-form-item">' +
            '<label class="layui-form-label">列配置</label>' +
            '<div class="layui-input-block">';

        // 每个列的配置面板
        $.each(element.columns, function (index, column) {
            html += '<div class="column-item" style="margin-bottom:15px;border:1px solid #e8e8e8;padding:10px;border-radius:2px;">' +
                '<div class="column-header" style="display:flex;justify-content:space-between;margin-bottom:8px;">' +
                '<span>列 ' + (index + 1) + '</span>' +
                '<button type="button" class="layui-btn layui-btn-xs layui-btn-danger delete-column" data-index="' + index + '">' +
                '<i class="layui-icon layui-icon-delete"></i>' +
                '</button>' +
                '</div>' +

                // 列标题
                '<div class="layui-form-item" style="margin-bottom:8px;">' +
                '<input type="text" name="columnTitle_' + index + '" value="' + (column.title || '') + '" placeholder="列标题" class="layui-input">' +
                '</div>' +

                // 字段选择
                '<div class="layui-form-item" style="margin-bottom:8px;">' +
                '<div class="content-input-group">' +
                '<textarea name="columnField_' + index + '" placeholder="请输入内容,点击下方按钮选择变量" class="layui-textarea" rows="2">' + (column.field || '') + '</textarea>' +
                '<button type="button" class="layui-btn layui-btn-primary layui-btn-sm select-column-field" data-index="' + index + '" style="margin-top:5px;">' +
                '<i class="layui-icon layui-icon-template"></i> 选择字段' +
                '</button>' +
                '</div>' +
                '</div>' +

                // 列样式设置
                '<div class="column-style">' +
                '<div class="layui-row">' +
                // 宽度设置
                '<div class="layui-col-xs6">' +
                '<div class="layui-form-item" style="margin-bottom:8px;">' +
                '<div class="layui-input-inline" style="width:100%;">' +
                '<input type="number" name="columnWidth_' + index + '" value="' + (column.width || 100) + '" placeholder="宽度" min="50" max="1000" class="layui-input">' +
                '</div>' +
                '</div>' +
                '</div>' +
                // 对齐方式
                '<div class="layui-col-xs6">' +
                '<div class="layui-form-item" style="margin-bottom:8px;">' +
                '<div class="layui-input-inline" style="width:100%;">' +
                '<select name="columnAlign_' + index + '">' +
                '<option value="flex-start" ' + (column.align === 'flex-start' ? 'selected' : '') + '>左对齐</option>' +
                '<option value="center" ' + (column.align === 'center' ? 'selected' : '') + '>居中</option>' +
                '<option value="flex-end" ' + (column.align === 'flex-end' ? 'selected' : '') + '>右对齐</option>' +
                '</select>' +
                '</div>' +
                '</div>' +
                '</div>' +
                '</div>' +

                '<div class="layui-row">' +
                // 字体大小
                '<div class="layui-col-xs6">' +
                '<div class="layui-form-item" style="margin-bottom:8px;">' +
                '<div class="layui-input-inline" style="width:100%;">' +
                '<input type="number" name="columnFontSize_' + index + '" value="' + (column.fontSize || 14) + '" placeholder="字号" min="12" max="72" class="layui-input">' +
                '</div>' +
                '</div>' +
                '</div>' +
                // 自动换行
                '<div class="layui-col-xs6">' +
                '<div class="layui-form-item" style="margin-bottom:8px;">' +
                '<input type="checkbox" name="columnWrap_' + index + '" title="自动换行" lay-skin="primary" ' + (column.wrap ? 'checked' : '') + '>' +
                '</div>' +
                '</div>' +
                '</div>' +
                '</div>' +
                '</div>';
        });

        // 添加列按钮
        html += '<button type="button" class="layui-btn layui-btn-fluid layui-btn-normal add-column">添加列</button>' +
            '</div>' +
            '</div>';

        // 表格样式设置
        html += '<div class="layui-form-item layui-form-title">' +
            '<h3>表格样式</h3>' +
            '</div>' +
            '<div class="layui-form-item">' +
            '<label class="layui-form-label">是否显示表头</label>' +
            '<div class="layui-input-block">' +
            '<input type="checkbox" name="showHeader" lay-skin="switch" lay-text="是|否" ' + (element.showHeader ? 'checked' : '') + ' title="显示表头">' +
            '</div></div>' +
            '<div class="layui-form-item">' +
            '<label class="layui-form-label">斑马纹</label>' +
            '<div class="layui-input-block">' +
            '<input type="checkbox" name="zebra" lay-skin="switch" lay-text="是|否" ' + (element.zebra ? 'checked' : '') + ' title="斑马纹">' +
            '</div></div>' +
            '<div class="layui-form-item">' +
            '<label class="layui-form-label">行高</label>' +
            '<div class="layui-input-block">' +
            '<input type="number" name="rowHeight" value="' + (element.rowHeight || 40) + '" placeholder="行高" class="layui-input">' +
            '</div></div>' +
            // 表头颜色设置
            '<div class="layui-form-item">' +
            '<label class="layui-form-label">表头背景色</label>' +
            '<div class="layui-input-block">' +
            '<div id="headerBackgroundPicker"></div>' +
            '<input type="hidden" id="headerBackgroundInput" name="headerBackground" value="' + (element.headerBackground || '#f0f0f0') + '">' +
            '</div></div>' +
            // 表头文字色
            '<div class="layui-form-item">' +
            '<label class="layui-form-label">表头文字色</label>' +
            '<div class="layui-input-block">' +
            '<div id="headerColorPicker"></div>' +
            '<input type="hidden" id="headerColorInput" name="headerColor" value="' + (element.headerColor || '#333') + '">' +
            '</div></div>';

        return html;
    };

    /**
     * 渲染条码设置
     */
    PrintTemplateDesign.prototype.renderBarcodeSettings = function (element) {
        // 确保条码类型属性存在
        if (!element.barcodeType) {
            element.barcodeType = 'barcode';
        }

        // 条码类型选择
        var html = '<div class="layui-form-item">' +
            '<label class="layui-form-label">条码类型</label>' +
            '<div class="layui-input-block">' +
            '<select name="barcodeType" lay-filter="barcodeType">' +
            '<option value="barcode" ' + (element.barcodeType === 'barcode' ? 'selected' : '') + '>一维码</option>' +
            '<option value="qrcode" ' + (element.barcodeType === 'qrcode' ? 'selected' : '') + '>二维码</option>' +
            '</select>' +
            '</div>' +
            '</div>';

        // 根据条码类型显示不同选项
        if (element.barcodeType === 'barcode') {
            // 条码格式
            html += '<div class="layui-form-item">' +
                '<label class="layui-form-label">条码格式</label>' +
                '<div class="layui-input-block">' +
                '<select name="format">' +
                '<option value="CODE128" ' + (element.format === 'CODE128' ? 'selected' : '') + '>CODE128</option>' +
                '<option value="CODE39" ' + (element.format === 'CODE39' ? 'selected' : '') + '>CODE39</option>' +
                '<option value="EAN13" ' + (element.format === 'EAN13' ? 'selected' : '') + '>EAN-13</option>' +
                '<option value="EAN8" ' + (element.format === 'EAN8' ? 'selected' : '') + '>EAN-8</option>' +
                '<option value="UPC" ' + (element.format === 'UPC' ? 'selected' : '') + '>UPC-A</option>' +
                '<option value="ITF" ' + (element.format === 'ITF' ? 'selected' : '') + '>ITF</option>' +
                '<option value="MSI" ' + (element.format === 'MSI' ? 'selected' : '') + '>MSI</option>' +
                '</select>' +
                '</div>' +
                '</div>';

            // 显示文本
            html += '<div class="layui-form-item">' +
                '<label class="layui-form-label">显示文本</label>' +
                '<div class="layui-input-block">' +
                '<input type="checkbox" name="showLabel" lay-skin="switch" lay-text="是|否" ' + (element.showLabel ? 'checked' : '') + '>' +
                '</div>' +
                '</div>';

            // 文本位置选项 - 即使不显示文本，也保留这个设置，只是禁用
            html += '<div class="layui-form-item" id="textPositionSettings" ' + (!element.showLabel ? 'style="opacity:0.6;"' : '') + '>' +
                '<label class="layui-form-label">文本位置</label>' +
                '<div class="layui-input-block">' +
                '<select name="textPosition" ' + (!element.showLabel ? 'disabled' : '') + '>' +
                '<option value="bottom" ' + (element.textPosition === 'bottom' ? 'selected' : '') + '>底部</option>' +
                '<option value="top" ' + (element.textPosition === 'top' ? 'selected' : '') + '>顶部</option>' +
                '</select>' +
                '</div>' +
                '</div>';

            // 条码设置
            html += '<div class="layui-form-item">' +
                '<label class="layui-form-label">条码设置</label>' +
                '<div class="layui-input-block">' +
                '<div class="layui-row">' +
                '<div class="layui-col-xs6">' +
                '<input type="number" name="barWidth" value="' + (element.barWidth || 2) + '" min="1" max="4" class="layui-input" placeholder="条码宽度">' +
                '</div>' +
                '<div class="layui-col-xs6">' +
                '<input type="number" name="fontSize" value="' + (element.fontSize || 12) + '" min="10" max="20" class="layui-input" placeholder="字体大小">' +
                '</div>' +
                '</div>' +
                '</div>' +
                '</div>';
        } else {
            // 二维码纠错级别
            html += '<div class="layui-form-item">' +
                '<label class="layui-form-label">纠错级别</label>' +
                '<div class="layui-input-block">' +
                '<select name="errorLevel">' +
                '<option value="L" ' + (element.errorLevel === 'L' ? 'selected' : '') + '>低 (L)</option>' +
                '<option value="M" ' + (element.errorLevel === 'M' ? 'selected' : '') + '>中 (M)</option>' +
                '<option value="Q" ' + (element.errorLevel === 'Q' ? 'selected' : '') + '>高 (Q)</option>' +
                '<option value="H" ' + (element.errorLevel === 'H' ? 'selected' : '') + '>最高 (H)</option>' +
                '</select>' +
                '</div>' +
                '</div>';
        }

        // 条码内容
        html += '<div class="layui-form-item">' +
            '<label class="layui-form-label">条码内容</label>' +
            '<div class="layui-input-block">' +
            '<div class="layui-input-group">' +
            '<input type="text" name="value" value="' + (element.value || '') + '" class="layui-input">' +
            '<div class="layui-input-suffix">' +
            '<button type="button" class="layui-btn layui-btn-primary layui-btn-sm variable-selector-btn" data-target="value">' +
            '<i class="layui-icon layui-icon-template"></i> 插入变量' +
            '</button>' +
            '</div>' +
            '</div>' +
            '</div>' +
            '</div>';

        // 颜色配置
        html += '<div class="layui-form-item">' +
            '<label class="layui-form-label">前景色</label>' +
            '<div class="layui-input-block">' +
            '<div id="foregroundPicker"></div>' +
            '<input type="hidden" id="foregroundInput" name="foreground" value="' + (element.foreground || '#000000') + '">' +
            '</div>' +
            '</div>';

        html += '<div class="layui-form-item">' +
            '<label class="layui-form-label">背景色</label>' +
            '<div class="layui-input-block">' +
            '<div id="backgroundPicker"></div>' +
            '<input type="hidden" id="backgroundInput" name="background" value="' + (element.background || '#ffffff') + '">' +
            '</div>' +
            '</div>';

        return html;
    };

    /**
     * 渲染通用样式设置
     */
    PrintTemplateDesign.prototype.renderCommonStyleSettings = function (element) {
        var html = '<div class="layui-form-item layui-form-title">' +
            '<h3>通用样式设置</h3>' +
            '</div>';

        // 旋转
        html += '<div class="layui-form-item">' +
            '<label class="layui-form-label">旋转角度</label>' +
            '<div class="layui-input-block">' +
            '<div class="layui-row">' +
            '<div class="layui-col-xs8">' +
            '<input type="number" name="rotate" value="' + (element.rotate || 0) + '" min="-360" max="360" step="15" class="layui-input">' +
            '</div>' +
            '<div class="layui-col-xs4">' +
            '<select name="transformOrigin">' +
            '<option value="center" ' + (element.transformOrigin === 'center' ? 'selected' : '') + '>中心</option>' +
            '<option value="top left" ' + (element.transformOrigin === 'top left' ? 'selected' : '') + '>左上</option>' +
            '<option value="top right" ' + (element.transformOrigin === 'top right' ? 'selected' : '') + '>右上</option>' +
            '<option value="bottom left" ' + (element.transformOrigin === 'bottom left' ? 'selected' : '') + '>左下</option>' +
            '<option value="bottom right" ' + (element.transformOrigin === 'bottom right' ? 'selected' : '') + '>右下</option>' +
            '</select>' +
            '</div>' +
            '</div>' +
            '</div>' +
            '</div>';

        // 透明度
        html += '<div class="layui-form-item">' +
            '<label class="layui-form-label">透明度</label>' +
            '<div class="layui-input-block">' +
            '<div id="opacitySlider"></div>' +
            '<input type="hidden" name="opacity" id="opacityValue" value="' + (element.opacity || 100) + '">' +
            '</div>' +
            '</div>';

        // 阴影设置
        html += '<div class="layui-form-item">' +
            '<label class="layui-form-label">阴影</label>' +
            '<div class="layui-input-block">' +
            '<input type="checkbox" name="shadowEnabled" lay-skin="switch" lay-text="启用|关闭" ' +
            ((element.shadow && element.shadow.enabled) ? 'checked' : '') + ' lay-filter="shadowEnabled">' +
            '</div>' +
            '</div>';

        // 确保shadow对象存在
        if (!element.shadow) {
            element.shadow = {
                enabled: false,
                x: 0,
                y: 0,
                blur: 5,
                color: 'rgba(0,0,0,0.3)'
            };
        }

        // 阴影详细设置，仅在启用时显示
        var shadowDisplay = (element.shadow && element.shadow.enabled) ? '' : 'display:none;';
        html += '<div id="shadowSettings" style="' + shadowDisplay + '">' +
            '<div class="layui-form-item">' +
            '<label class="layui-form-label">X偏移</label>' +
            '<div class="layui-input-block">' +
            '<input type="number" name="shadowX" value="' + (element.shadow.x || 0) + '" class="layui-input">' +
            '</div>' +
            '</div>' +

            '<div class="layui-form-item">' +
            '<label class="layui-form-label">Y偏移</label>' +
            '<div class="layui-input-block">' +
            '<input type="number" name="shadowY" value="' + (element.shadow.y || 0) + '" class="layui-input">' +
            '</div>' +
            '</div>' +

            '<div class="layui-form-item">' +
            '<label class="layui-form-label">模糊</label>' +
            '<div class="layui-input-block">' +
            '<input type="number" name="shadowBlur" value="' + (element.shadow.blur || 5) + '" min="0" class="layui-input">' +
            '</div>' +
            '</div>' +

            '<div class="layui-form-item">' +
            '<label class="layui-form-label">阴影颜色</label>' +
            '<div class="layui-input-block">' +
            '<div id="shadowColorPicker"></div>' +
            '<input type="hidden" id="shadowColorInput" name="shadowColor" value="' + (element.shadow.color || 'rgba(0,0,0,0.3)') + '">' +
            '</div>' +
            '</div>' +
            '</div>';

        // 背景色
        html += '<div class="layui-form-item">' +
            '<label class="layui-form-label">背景色</label>' +
            '<div class="layui-input-block">' +
            '<div id="backgroundColorPicker"></div>' +
            '<input type="hidden" id="backgroundColorInput" name="backgroundColor" value="' + (element.backgroundColor || '') + '">' +
            '</div>' +
            '</div>';

        // 边框
        html += '<div class="layui-form-item">' +
            '<label class="layui-form-label">边框样式</label>' +
            '<div class="layui-input-block">' +
            '<select name="borderStyle" lay-filter="borderStyle">' +
            '<option value="none" ' + (element.borderStyle === 'none' ? 'selected' : '') + '>无</option>' +
            '<option value="solid" ' + (element.borderStyle === 'solid' ? 'selected' : '') + '>实线</option>' +
            '<option value="dashed" ' + (element.borderStyle === 'dashed' ? 'selected' : '') + '>虚线</option>' +
            '<option value="dotted" ' + (element.borderStyle === 'dotted' ? 'selected' : '') + '>点线</option>' +
            '</select>' +
            '</div>' +
            '</div>';

        // 边框宽度和颜色
        var borderDisplay = element.borderStyle === 'none' ? 'display:none;' : '';
        html += '<div id="borderSettings" style="' + borderDisplay + '">' +
            '<div class="layui-form-item">' +
            '<label class="layui-form-label">边框宽度</label>' +
            '<div class="layui-input-block">' +
            '<input type="number" name="borderWidth" value="' + (element.borderWidth || 1) + '" min="0" max="10" class="layui-input">' +
            '</div>' +
            '</div>' +

            '<div class="layui-form-item">' +
            '<label class="layui-form-label">边框颜色</label>' +
            '<div class="layui-input-block">' +
            '<div id="borderColorPicker"></div>' +
            '<input type="hidden" id="borderColorInput" name="borderColor" value="' + (element.borderColor || '#d9d9d9') + '">' +
            '</div>' +
            '</div>' +
            '</div>';

        // 圆角
        html += '<div class="layui-form-item">' +
            '<label class="layui-form-label">圆角</label>' +
            '<div class="layui-input-block">' +
            '<div class="layui-row">' +
            '<div class="layui-col-xs8">' +
            '<input type="number" name="borderRadius" value="' + (element.borderRadius || 0) + '" min="0" max="100" class="layui-input">' +
            '</div>' +
            '<div class="layui-col-xs4">' +
            '<select name="borderRadiusUnit">' +
            '<option value="px" ' + (element.borderRadiusUnit === 'px' ? 'selected' : '') + '>px</option>' +
            '<option value="%" ' + (element.borderRadiusUnit === '%' ? 'selected' : '') + '>%</option>' +
            '</select>' +
            '</div>' +
            '</div>' +
            '</div>' +
            '</div>';

        return html;
    };

    /**
     * 保存到历史记录
     */
    PrintTemplateDesign.prototype.saveToHistory = function () {
        var self = this;
        self.history.past.push(JSON.stringify(self.elements));
        self.history.future = [];

        // 更新撤销/重做按钮状态
        self.updateUndoRedoState();
    };

    /**
     * 更新撤销/重做按钮状态
     */
    PrintTemplateDesign.prototype.updateUndoRedoState = function () {
        var self = this;

        if (self.history.past.length > 0) {
            $('#undoBtn').prop('disabled', false);
        } else {
            $('#undoBtn').prop('disabled', true);
        }

        if (self.history.future.length > 0) {
            $('#redoBtn').prop('disabled', false);
        } else {
            $('#redoBtn').prop('disabled', true);
        }
    };

    /**
     * 处理撤销
     */
    PrintTemplateDesign.prototype.handleUndo = function () {
        var self = this;
        if (self.history.past.length === 0) return;

        var currentState = JSON.stringify(self.elements);
        self.history.future.push(currentState);
        self.elements = JSON.parse(self.history.past.pop());
        self.currentElement = null;
        self.selectedElements = [];

        // 更新撤销/重做按钮状态
        self.updateUndoRedoState();

        // 重新渲染
        self.renderElements();
    };

    /**
     * 处理重做
     */
    PrintTemplateDesign.prototype.handleRedo = function () {
        var self = this;
        if (self.history.future.length === 0) return;

        var currentState = JSON.stringify(self.elements);
        self.history.past.push(currentState);
        self.elements = JSON.parse(self.history.future.pop());
        self.currentElement = null;
        self.selectedElements = [];

        // 更新撤销/重做按钮状态
        self.updateUndoRedoState();

        // 重新渲染
        self.renderElements();
    };

    /**
     * 处理元素鼠标按下
     */
    PrintTemplateDesign.prototype.handleElementMouseDown = function (e, element) {
        var self = this;

        // 如果元素被锁定，不处理
        if (element.locked) return;

        // 处理多选
        if (e.ctrlKey || e.metaKey) {
            var index = self.selectedElements.findIndex(function (el) { return el.id === element.id; });
            if (index > -1) {
                self.selectedElements.splice(index, 1);
            } else {
                self.selectedElements.push(element);
            }
            self.currentElement = element;
        } else {
            self.selectedElements = [element];
            self.currentElement = element;
        }

        // 更新选中状态
        $('.design-element').removeClass('active');
        $.each(self.selectedElements, function (i, el) {
            $('.design-element[data-id="' + el.id + '"]').addClass('active');
        });

        // 更新属性面板
        self.updatePropertyPanel();

        // 如果选中多个元素，显示组合控制按钮
        if (self.selectedElements.length > 1) {
            $('#groupControls').show();
        } else {
            $('#groupControls').hide();
        }

        // 获取画布和元素的初始信息
        var paperRect = $('#paper')[0].getBoundingClientRect();

        // 计算鼠标相对于元素的偏移
        var startLeft = element.x;
        var startTop = element.y;

        // 计算鼠标在元素内的相对位置（考虑缩放）
        var mouseOffsetX = (e.clientX - paperRect.left) / self.scale - element.x;
        var mouseOffsetY = (e.clientY - paperRect.top) / self.scale - element.y;

        var handleMouseMove = function (e) {
            // 计算新位置（考虑缩放和滚动）
            var clientX = e.clientX || 0;
            var clientY = e.clientY || 0;

            var newX = (clientX - paperRect.left) / self.scale - mouseOffsetX;
            var newY = (clientY - paperRect.top) / self.scale - mouseOffsetY;

            // 确保坐标有效
            if (isNaN(newX) || isNaN(newY)) {
                return;
            }

            // 对齐到网格
            if (!e.shiftKey) {
                newX = Math.round(newX / 10) * 10;
                newY = Math.round(newY / 10) * 10;
            }

            // 计算对齐线
            self.alignLines = { vertical: [], horizontal: [] };
            $.each(self.elements, function (i, other) {
                if (other.id === element.id) return;

                // 垂直对齐
                if (Math.abs(newX - other.x) < 5) {
                    self.alignLines.vertical.push(other.x);
                    newX = other.x;
                }
                if (Math.abs((newX + element.width) - (other.x + other.width)) < 5) {
                    self.alignLines.vertical.push(other.x + other.width - element.width);
                    newX = other.x + other.width - element.width;
                }

                // 水平对齐
                if (Math.abs(newY - other.y) < 5) {
                    self.alignLines.horizontal.push(other.y);
                    newY = other.y;
                }
                if (Math.abs((newY + element.height) - (other.y + other.height)) < 5) {
                    self.alignLines.horizontal.push(other.y + other.height - element.height);
                    newY = other.y + other.height - element.height;
                }
            });

            // 更新元素位置
            element.x = Math.max(0, newX);
            element.y = Math.max(0, newY);

            // 如果是多选，同时移动其他选中的元素
            if (self.selectedElements.length > 1) {
                var deltaX = element.x - startLeft;
                var deltaY = element.y - startTop;
                $.each(self.selectedElements, function (i, el) {
                    if (el.id !== element.id) {
                        el.x += deltaX;
                        el.y += deltaY;
                    }
                });
            }

            // 渲染对齐线
            self.renderAlignLines();

            // 更新元素位置
            $('.design-element[data-id="' + element.id + '"]').css({
                left: element.x + 'px',
                top: element.y + 'px'
            });

            // 更新多选元素位置
            if (self.selectedElements.length > 1) {
                $.each(self.selectedElements, function (i, el) {
                    if (el.id !== element.id) {
                        $('.design-element[data-id="' + el.id + '"]').css({
                            left: el.x + 'px',
                            top: el.y + 'px'
                        });
                    }
                });
            }
        };

        var handleMouseUp = function () {
            $(document).off('mousemove', handleMouseMove);
            $(document).off('mouseup', handleMouseUp);

            // 清除对齐线
            self.alignLines = { vertical: [], horizontal: [] };
            self.renderAlignLines();

            // 保存历史记录
            self.saveToHistory();

            // 重新渲染元素
            self.renderElements();
        };

        $(document).on('mousemove', handleMouseMove);
        $(document).on('mouseup', handleMouseUp);
    };

    /**
     * 渲染对齐线
     */
    PrintTemplateDesign.prototype.renderAlignLines = function () {
        var self = this;
        var alignLinesContainer = $('#alignLines');
        alignLinesContainer.empty();

        // 渲染垂直对齐线
        $.each(self.alignLines.vertical, function (i, line) {
            alignLinesContainer.append('<div class="align-line vertical" style="left:' + line + 'px;"></div>');
        });

        // 渲染水平对齐线
        $.each(self.alignLines.horizontal, function (i, line) {
            alignLinesContainer.append('<div class="align-line horizontal" style="top:' + line + 'px;"></div>');
        });
    };

    /**
     * 处理缩放鼠标按下
     */
    PrintTemplateDesign.prototype.handleResizeMouseDown = function (e, element) {
        var self = this;
        e.stopPropagation();

        var startX = e.clientX;
        var startY = e.clientY;
        var startWidth = element.width;
        var startHeight = element.height;

        var handleMouseMove = function (e) {
            var deltaX = e.clientX - startX;
            var deltaY = e.clientY - startY;

            // 计算新尺寸
            element.width = Math.max(30, startWidth + deltaX);
            element.height = Math.max(30, startHeight + deltaY);

            // 更新元素样式
            $('.design-element[data-id="' + element.id + '"]').css({
                width: element.width + 'px',
                height: element.height + 'px'
            });
        };

        var handleMouseUp = function () {
            $(document).off('mousemove', handleMouseMove);
            $(document).off('mouseup', handleMouseUp);

            // 保存历史记录
            self.saveToHistory();

            // 重新渲染元素
            self.renderElements();

            // 更新属性面板
            self.updatePropertyPanel();
        };

        $(document).on('mousemove', handleMouseMove);
        $(document).on('mouseup', handleMouseUp);
    };

    /**
     * 处理旋转鼠标按下
     */
    PrintTemplateDesign.prototype.handleRotateMouseDown = function (e, element) {
        var self = this;
        e.stopPropagation();

        var paperRect = $('#paper')[0].getBoundingClientRect();
        var centerX = element.x + element.width / 2;
        var centerY = element.y + element.height / 2;

        var handleMouseMove = function (e) {
            var x = e.clientX - paperRect.left - centerX;
            var y = e.clientY - paperRect.top - centerY;
            var angle = Math.atan2(y, x) * (180 / Math.PI);

            // 计算旋转角度，并对齐到15度
            var rotate = Math.round((angle + 90) / 15) * 15;
            if (e.shiftKey) {
                rotate = Math.round(rotate / 45) * 45;
            }

            element.rotate = rotate;

            // 更新元素样式
            $('.design-element[data-id="' + element.id + '"]').css({
                transform: 'rotate(' + rotate + 'deg)'
            });
        };

        var handleMouseUp = function () {
            $(document).off('mousemove', handleMouseMove);
            $(document).off('mouseup', handleMouseUp);

            // 保存历史记录
            self.saveToHistory();

            // 重新渲染元素
            self.renderElements();

            // 更新属性面板
            self.updatePropertyPanel();
        };

        $(document).on('mousemove', handleMouseMove);
        $(document).on('mouseup', handleMouseUp);
    };

    /**
     * 处理右键菜单
     */
    PrintTemplateDesign.prototype.handleContextMenu = function (e, element) {
        var self = this;
        e.preventDefault();

        self.contextMenu = {
            visible: true,
            x: e.clientX,
            y: e.clientY,
            element: element
        };

        // 选中元素
        self.selectElement(element);

        // 显示右键菜单
        $('#contextMenu').css({
            left: e.clientX + 'px',
            top: e.clientY + 'px',
            display: 'block'
        });

        // 更新锁定文本
        $('#lockText').text(element.locked ? '解锁' : '锁定');
    };

    /**
     * 关闭右键菜单
     */
    PrintTemplateDesign.prototype.closeContextMenu = function () {
        var self = this;
        self.contextMenu.visible = false;
        $('#contextMenu').hide();
    };

    /**
     * 处理复制
     */
    PrintTemplateDesign.prototype.handleCopy = function () {
        var self = this;
        if (!self.contextMenu.element) return;

        var element = self.contextMenu.element;
        var newElement = $.extend(true, {}, element, {
            id: Date.now(),
            x: element.x + 20,
            y: element.y + 20,
            animation: element.animation || {
                type: 'none',
                duration: 500,
                delay: 0,
                direction: 'top'
            },
            shadow: element.shadow || {
                enabled: false,
                x: 0,
                y: 0,
                blur: 5,
                color: 'rgba(0,0,0,0.3)'
            }
        });

        // 添加新元素
        self.elements.push(newElement);
        self.currentElement = newElement;
        self.selectedElements = [newElement];

        // 保存历史记录
        self.saveToHistory();

        // 关闭右键菜单
        self.closeContextMenu();

        // 重新渲染
        self.renderElements();
    };

    /**
     * 处理删除
     */
    PrintTemplateDesign.prototype.handleDelete = function () {
        var self = this;
        var element = self.contextMenu.element || self.currentElement;
        if (!element) return;

        var index = self.elements.findIndex(function (el) { return el.id === element.id; });
        if (index > -1) {
            self.elements.splice(index, 1);
            self.currentElement = null;
            self.selectedElements = [];
        }

        // 保存历史记录
        self.saveToHistory();

        // 关闭右键菜单
        self.closeContextMenu();

        // 重新渲染
        self.renderElements();

        // 清空属性面板
        self.updatePropertyPanel();
    };

    /**
     * 置于顶层
     */
    PrintTemplateDesign.prototype.bringToFront = function () {
        var self = this;
        var element = self.contextMenu.element || self.currentElement;
        if (!element) return;

        var index = self.elements.findIndex(function (el) { return el.id === element.id; });
        if (index > -1) {
            var el = self.elements.splice(index, 1)[0];
            self.elements.push(el);
        }

        // 关闭右键菜单
        self.closeContextMenu();

        // 重新渲染
        self.renderElements();
    };

    /**
     * 置于底层
     */
    PrintTemplateDesign.prototype.sendToBack = function () {
        var self = this;
        var element = self.contextMenu.element || self.currentElement;
        if (!element) return;

        var index = self.elements.findIndex(function (el) { return el.id === element.id; });
        if (index > -1) {
            var el = self.elements.splice(index, 1)[0];
            self.elements.unshift(el);
        }

        // 关闭右键菜单
        self.closeContextMenu();

        // 重新渲染
        self.renderElements();
    };

    /**
     * 处理锁定元素
     */
    PrintTemplateDesign.prototype.handleLockElement = function () {
        var self = this;
        var element = self.contextMenu.element || self.currentElement;
        if (!element) return;

        element.locked = !element.locked;

        // 保存历史记录
        self.saveToHistory();

        // 关闭右键菜单
        self.closeContextMenu();

        // 重新渲染
        self.renderElements();
    };

    /**
     * 处理元素对齐
     */
    PrintTemplateDesign.prototype.alignElements = function (type) {
        var self = this;
        if (self.selectedElements.length < 2) return;

        var firstElement = self.selectedElements[0];
        var others = self.selectedElements.slice(1);

        switch (type) {
            case 'left':
                $.each(others, function (i, element) {
                    element.x = firstElement.x;
                });
                break;

            case 'center':
                var centerX = firstElement.x + firstElement.width / 2;
                $.each(others, function (i, element) {
                    element.x = centerX - element.width / 2;
                });
                break;

            case 'right':
                var rightX = firstElement.x + firstElement.width;
                $.each(others, function (i, element) {
                    element.x = rightX - element.width;
                });
                break;
        }

        // 保存历史记录
        self.saveToHistory();

        // 重新渲染
        self.renderElements();
    };

    /**
     * 元素组合
     */
    PrintTemplateDesign.prototype.groupElements = function () {
        var self = this;
        if (self.selectedElements.length < 2) return;

        var ids = self.selectedElements.map(function (el) { return el.id; });
        var groupElements = self.elements.filter(function (el) {
            return ids.indexOf(el.id) > -1;
        });

        // 计算组边界
        var bounds = {
            left: Infinity,
            top: Infinity,
            right: -Infinity,
            bottom: -Infinity
        };

        $.each(groupElements, function (i, el) {
            bounds.left = Math.min(bounds.left, el.x);
            bounds.top = Math.min(bounds.top, el.y);
            bounds.right = Math.max(bounds.right, el.x + el.width);
            bounds.bottom = Math.max(bounds.bottom, el.y + el.height);
        });

        // 创建组
        var group = {
            id: Date.now(),
            type: 'group',
            x: bounds.left,
            y: bounds.top,
            width: bounds.right - bounds.left,
            height: bounds.bottom - bounds.top,
            children: groupElements.map(function (el) {
                return $.extend({}, el, {
                    x: el.x - bounds.left,
                    y: el.y - bounds.top
                });
            })
        };

        // 移除原始元素并添加组
        self.elements = self.elements.filter(function (el) {
            return ids.indexOf(el.id) === -1;
        });
        self.elements.push(group);

        // 更新选中元素
        self.selectedElements = [group];
        self.currentElement = group;

        // 保存历史记录
        self.saveToHistory();

        // 重新渲染
        self.renderElements();
    };

    /**
     * 处理元素放置
     */
    PrintTemplateDesign.prototype.handleDrop = function (e) {
        var self = this;
        var type = e.originalEvent.dataTransfer.getData('widgetType');
        var rect = $('#paper')[0].getBoundingClientRect();

        // 修复NaN问题：确保坐标是有效的数值并考虑缩放因素
        var x = Math.round((e.clientX - rect.left) / self.scale);
        var y = Math.round((e.clientY - rect.top) / self.scale);

        // 检查坐标是否有效
        if (isNaN(x) || isNaN(y)) {
            // 使用默认坐标
            x = 50;
            y = 50;
        }

        // 创建新元素
        var element = {
            id: Date.now(),
            type: type,
            x: x,
            y: y
        };

        // 合并默认配置
        $.extend(element, self.getDefaultConfig(type));

        // 对齐到网格并确保值是数值类型
        element.x = Math.round(element.x / 10) * 10;
        element.y = Math.round(element.y / 10) * 10;

        // 确保其他关键属性是数值类型
        element.width = parseInt(element.width) || 100;
        element.height = parseInt(element.height) || 40;

        // 添加元素
        self.elements.push(element);

        // 保存历史记录
        self.saveToHistory();

        // 选中元素
        self.selectElement(element);

        // 重新渲染
        self.renderElements();
    };

    /**
     * 选择元素
     */
    PrintTemplateDesign.prototype.selectElement = function (element) {
        var self = this;
        self.currentElement = element;

        // 更新选中元素数组
        if (!self.selectedElements.find(function (el) { return el.id === element.id; })) {
            self.selectedElements = [element];
        }

        // 更新属性面板
        self.updatePropertyPanel();

        // 更新元素选中状态
        $('.design-element').removeClass('active');
        $('.design-element[data-id="' + element.id + '"]').addClass('active');
    };

    /**
     * 处理设计区域鼠标按下
     */
    PrintTemplateDesign.prototype.handleDesignAreaMouseDown = function (e) {
        var self = this;

        // 只响应鼠标左键
        if (e.button !== 0) return;

        // 如果点击的是元素或其他控件，不处理拖拽
        if (e.target !== $('#designArea')[0] && e.target !== $('#paper')[0]) return;

        // 取消元素选中
        self.currentElement = null;
        self.selectedElements = [];
        $('.design-element').removeClass('active');
        self.updatePropertyPanel();

        // 隐藏组合控制按钮
        $('#groupControls').hide();

        var startX = e.clientX;
        var startY = e.clientY;
        var designArea = $('#designArea');
        var startScrollLeft = designArea.scrollLeft();
        var startScrollTop = designArea.scrollTop();

        // 修改鼠标样式
        $('body').css('cursor', 'grabbing');

        var handleMouseMove = function (e) {
            // 计算新的滚动位置
            var newScrollLeft = startScrollLeft + (startX - e.clientX);
            var newScrollTop = startScrollTop + (startY - e.clientY);

            // 更新滚动位置
            designArea.scrollLeft(newScrollLeft);
            designArea.scrollTop(newScrollTop);

            // 更新标尺
            self.updateRulers();
        };

        var handleMouseUp = function () {
            $('body').css('cursor', '');
            $(document).off('mousemove', handleMouseMove);
            $(document).off('mouseup', handleMouseUp);
        };

        $(document).on('mousemove', handleMouseMove);
        $(document).on('mouseup', handleMouseUp);
    };

    /**
     * 处理鼠标滚轮缩放
     */
    PrintTemplateDesign.prototype.handleWheel = function (e) {
        var self = this;
        if (!e.ctrlKey) return;

        e.preventDefault();

        var delta = e.originalEvent.deltaY > 0 ? -config.scaleConfig.scaleStep : config.scaleConfig.scaleStep;
        var newScale = Math.min(
            Math.max(self.scale + delta, config.scaleConfig.minScale),
            config.scaleConfig.maxScale
        );

        self.scale = Number(newScale.toFixed(2));

        // 更新缩放显示
        $('#scaleDisplay').text(Math.round(self.scale * 100) + '%');

        // 更新纸张缩放
        $('#paper').css('transform', 'scale(' + self.scale + ')');

        // 更新标尺
        self.updateRulers();
    };

    /**
     * 更新标尺
     */
    PrintTemplateDesign.prototype.updateRulers = function () {
        var self = this;

        var hRuler = document.getElementById('hRuler');
        var vRuler = document.getElementById('vRuler');

        if (!hRuler || !vRuler) return;

        var hCtx = hRuler.getContext('2d');
        var vCtx = vRuler.getContext('2d');

        var designAreaRect = $('#designArea')[0].getBoundingClientRect();

        // 设置画布尺寸
        hRuler.width = designAreaRect.width - 20;
        hRuler.height = 20;
        vRuler.width = 20;
        vRuler.height = designAreaRect.height - 20;

        // 获取滚动位置
        var scrollLeft = $('#designArea').scrollLeft();
        var scrollTop = $('#designArea').scrollTop();

        // 绘制背景
        hCtx.fillStyle = config.rulerStyle.backgroundColor;
        hCtx.fillRect(0, 0, hRuler.width, hRuler.height);
        vCtx.fillStyle = config.rulerStyle.backgroundColor;
        vCtx.fillRect(0, 0, vRuler.width, vRuler.height);

        // 计算刻度间隔（考虑缩放）
        var baseInterval = 10; // 10px为基础刻度

        // 绘制水平标尺
        hCtx.save();
        hCtx.translate(-scrollLeft * self.scale, 0);

        var startX = Math.floor(scrollLeft / baseInterval) * baseInterval;
        var endX = startX + (hRuler.width / self.scale) + baseInterval * 20;

        for (var i = startX; i <= endX; i += baseInterval) {
            var x = i * self.scale;
            var isMajor = i % (baseInterval * 10) === 0;
            var isMiddle = i % (baseInterval * 5) === 0;

            hCtx.beginPath();
            hCtx.strokeStyle = isMajor ? config.rulerStyle.majorLineColor : config.rulerStyle.lineColor;
            hCtx.lineWidth = isMajor ? 1 : 0.5;

            if (isMajor || isMiddle) {
                hCtx.moveTo(x, 0);
                hCtx.lineTo(x, isMajor ? 20 : 15);
            } else {
                hCtx.moveTo(x, 12);
                hCtx.lineTo(x, 20);
            }
            hCtx.stroke();

            if (isMajor) {
                hCtx.fillStyle = config.rulerStyle.textColor;
                hCtx.font = '10px Arial';
                hCtx.textAlign = 'left';
                hCtx.fillText(i.toString(), x, 10);
            }
        }

        hCtx.restore();

        // 绘制垂直标尺
        vCtx.save();
        vCtx.translate(0, -scrollTop * self.scale);

        var startY = Math.floor(scrollTop / baseInterval) * baseInterval;
        var endY = startY + (vRuler.height / self.scale) + baseInterval * 20;

        for (var i = startY; i <= endY; i += baseInterval) {
            var y = i * self.scale;
            var isMajor = i % (baseInterval * 10) === 0;
            var isMiddle = i % (baseInterval * 5) === 0;

            vCtx.beginPath();
            vCtx.strokeStyle = isMajor ? config.rulerStyle.majorLineColor : config.rulerStyle.lineColor;
            vCtx.lineWidth = isMajor ? 1 : 0.5;

            if (isMajor || isMiddle) {
                vCtx.moveTo(0, y);
                vCtx.lineTo(isMajor ? 20 : 15, y);
            } else {
                vCtx.moveTo(12, y);
                vCtx.lineTo(20, y);
            }
            vCtx.stroke();

            if (isMajor) {
                vCtx.save();
                vCtx.fillStyle = config.rulerStyle.textColor;
                vCtx.translate(15, y);
                vCtx.rotate(-Math.PI / 2);
                vCtx.font = '10px Arial';
                vCtx.textAlign = 'right';
                vCtx.fillText(i.toString(), 0, 4);
                vCtx.restore();
            }
        }

        vCtx.restore();
    };

    /**
     * 处理键盘事件
     */
    PrintTemplateDesign.prototype.handleKeyDown = function (e) {
        var self = this;
        if (!self.currentElement) return;

        var step = e.shiftKey ? 10 : 1;

        // 旋转快捷键
        if (e.altKey) {
            switch (e.key) {
                case 'ArrowLeft':
                    e.preventDefault();
                    self.currentElement.rotate = ((self.currentElement.rotate || 0) - 15) % 360;
                    break;
                case 'ArrowRight':
                    e.preventDefault();
                    self.currentElement.rotate = ((self.currentElement.rotate || 0) + 15) % 360;
                    break;
            }
        }

        // 复制和粘贴增强
        if (e.ctrlKey || e.metaKey) {
            switch (e.key.toLowerCase()) {
                case 'd':
                    e.preventDefault();
                    self.handleDuplicate();
                    break;
                case 'g':
                    e.preventDefault();
                    if (self.selectedElements.length > 1) {
                        self.groupElements();
                    }
                    break;
                case 'b':
                    e.preventDefault();
                    if (e.shiftKey) {
                        self.bringToFront();
                    } else {
                        self.sendToBack();
                    }
                    break;
            }
        }

        if (e.key === 'Delete') {
            self.handleDelete();
        }

        if (e.key === 'ArrowLeft') {
            e.preventDefault();
            self.currentElement.x -= step;
        }
        if (e.key === 'ArrowRight') {
            e.preventDefault();
            self.currentElement.x += step;
        }
        if (e.key === 'ArrowUp') {
            e.preventDefault();
            self.currentElement.y -= step;
        }
        if (e.key === 'ArrowDown') {
            e.preventDefault();
            self.currentElement.y += step;
        }

        if (['ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown'].includes(e.key)) {
            // 更新元素位置
            $('.design-element[data-id="' + self.currentElement.id + '"]').css({
                left: self.currentElement.x + 'px',
                top: self.currentElement.y + 'px'
            });

            self.saveToHistory();
        }

        if (e.ctrlKey || e.metaKey) {
            switch (e.key.toLowerCase()) {
                case 'c':
                    e.preventDefault();
                    self.handleCopy();
                    break;
                case 'z':
                    e.preventDefault();
                    if (e.shiftKey) {
                        self.handleRedo();
                    } else {
                        self.handleUndo();
                    }
                    break;
            }
        }
    };

    /**
     * 处理复制元素
     */
    PrintTemplateDesign.prototype.handleDuplicate = function () {
        var self = this;
        if (!self.currentElement) return;

        var element = self.currentElement;
        var newElement = $.extend(true, {}, element, {
            id: Date.now(),
            x: element.x + 20,
            y: element.y + 20,
            animation: element.animation || {
                type: 'none',
                duration: 500,
                delay: 0,
                direction: 'top'
            },
            shadow: element.shadow || {
                enabled: false,
                x: 0,
                y: 0,
                blur: 5,
                color: 'rgba(0,0,0,0.3)'
            }
        });

        // 添加新元素
        self.elements.push(newElement);
        self.currentElement = newElement;
        self.selectedElements = [newElement];

        // 保存历史记录
        self.saveToHistory();

        // 重新渲染
        self.renderElements();
    };

    /**
     * 显示打印设置模态框
     */
    PrintTemplateDesign.prototype.showPrintSettingsModal = function () {
        var self = this;

        // 更新表单
        self.updatePrintSettingsForm();

        // 显示模态框
        layer.open({
            type: 1,
            title: '打印设置',
            content: $('#printSettingsModal'),
            area: ['500px', '400px'],
            btn: ['确定', '取消'],
            yes: function (index) {
                self.handlePrintSettingsSave();
                layer.close(index);
            }
        });
    };

    /**
     * 处理打印设置保存
     */
    PrintTemplateDesign.prototype.handlePrintSettingsSave = function () {
        var self = this;

        // 获取表单数据
        var paperSize = $('#paperSize').val() || 'A4_PAGE';  // 确保有默认值
        var orientation = $('#orientation').val() || 'portrait';
        var width = $('#paperWidth').val() || '210';
        var height = $('#paperHeight').val() || '297';
        var marginTop = $('#marginTop').val() || '10';
        var marginRight = $('#marginRight').val() || '10';
        var marginBottom = $('#marginBottom').val() || '10';
        var marginLeft = $('#marginLeft').val() || '10';

        // 更新打印设置
        self.printSettings = {
            paperSize: paperSize,
            orientation: orientation,
            width: parseFloat(width),
            height: parseFloat(height),
            margin: {
                top: parseFloat(marginTop),
                right: parseFloat(marginRight),
                bottom: parseFloat(marginBottom),
                left: parseFloat(marginLeft)
            }
        };

        // 确保设置有效
        if (!self.printSettings.paperSize) {
            self.printSettings.paperSize = 'A4_PAGE';
        }

        // 更新纸张样式
        self.updatePaperStyle();

        // 保存设置
        self.handleSave(false)
            .then(function () {
                // 成功后关闭模态框
                layer.closeAll();
            })
            .catch(function (err) {
                console.error('保存打印设置失败:', err);
            });
    };

    /**
 * 初始化颜色选择器
 */
    PrintTemplateDesign.prototype.initColorPickers = function (element) {
        var self = this;

        // 文本颜色选择器
        if (element.type === 'text') {
            if ($('#textColorPicker').length > 0) {
                colorpicker.render({
                    elem: '#textColorPicker',
                    color: element.color || '#000000',
                    done: function (color) {
                        $('#textColorInput').val(color);
                        element.color = color;
                        self.renderElements();
                    }
                });
            }
        }

        // 表格表头颜色选择器
        if (element.type === 'table') {
            // 表头背景色
            if ($('#headerBackgroundPicker').length > 0) {
                colorpicker.render({
                    elem: '#headerBackgroundPicker',
                    color: element.headerBackground || '#f0f0f0',
                    done: function (color) {
                        $('#headerBackgroundInput').val(color);
                        element.headerBackground = color;
                        self.renderElements();
                    }
                });
            }

            // 表头文字色
            if ($('#headerColorPicker').length > 0) {
                colorpicker.render({
                    elem: '#headerColorPicker',
                    color: element.headerColor || '#333',
                    done: function (color) {
                        $('#headerColorInput').val(color);
                        element.headerColor = color;
                        self.renderElements();
                    }
                });
            }
        }

        // 通用颜色选择器 - 阴影颜色
        if ($('#shadowColorPicker').length > 0) {
            colorpicker.render({
                elem: '#shadowColorPicker',
                color: element.shadow && element.shadow.color ? element.shadow.color : 'rgba(0,0,0,0.3)',
                done: function (color) {
                    $('#shadowColorInput').val(color);
                    if (!element.shadow) {
                        element.shadow = {
                            enabled: true,
                            x: 0,
                            y: 0,
                            blur: 5,
                            color: color
                        };
                    } else {
                        element.shadow.color = color;
                    }
                    self.renderElements();
                }
            });
        }

        // 条码颜色选择器
        if (element.type === 'barcode') {
            // 前景色
            if ($('#foregroundPicker').length > 0) {
                colorpicker.render({
                    elem: '#foregroundPicker',
                    color: element.foreground || '#000000',
                    done: function (color) {
                        $('#foregroundInput').val(color);
                        element.foreground = color;
                        self.renderElements();
                    }
                });
            }

            // 背景色
            if ($('#backgroundPicker').length > 0) {
                colorpicker.render({
                    elem: '#backgroundPicker',
                    color: element.background || '#ffffff',
                    done: function (color) {
                        $('#backgroundInput').val(color);
                        element.background = color;
                        self.renderElements();
                    }
                });
            }
        }

        // 通用样式颜色选择器
        // 背景色
        if ($('#backgroundColorPicker').length > 0) {
            colorpicker.render({
                elem: '#backgroundColorPicker',
                color: element.backgroundColor || '',
                done: function (color) {
                    $('#backgroundColorInput').val(color);
                    element.backgroundColor = color;
                    self.renderElements();
                }
            });
        }

        // 边框颜色
        if ($('#borderColorPicker').length > 0) {
            colorpicker.render({
                elem: '#borderColorPicker',
                color: element.borderColor || '#d9d9d9',
                done: function (color) {
                    $('#borderColorInput').val(color);
                    element.borderColor = color;
                    self.renderElements();
                }
            });
        }

        // 初始化透明度滑块
        if ($('#opacitySlider').length > 0) {
            slider.render({
                elem: '#opacitySlider',
                value: element.opacity || 100,
                min: 0,
                max: 100,
                change: function (value) {
                    $('#opacityValue').val(value);
                    element.opacity = value;
                    self.renderElements();
                }
            });
        }
    };

    /**
     * 获取业务字段
     */
    PrintTemplateDesign.prototype.fetchBusinessFields = function () {
        var self = this;

        AjaxPostUtil.request({
            url: reqBasePath + 'queryAttrDefinitionList',
            params: { className: self.options.businessClassName, appId: self.options.appId },
            type: 'json',
            method: 'POST',
            callback: function (json) {
                self.businessFields = json.rows || [];
            },
            async: false
        });
    };

    /**
     * 显示变量选择器
     */
    PrintTemplateDesign.prototype.showVariableSelector = function (targetField) {
        var self = this;
        self.currentField = targetField; // 存储当前字段

        // 渲染变量列表
        self.renderVariableList();

        // 显示模态框
        layer.open({
            type: 1,
            title: '选择变量',
            content: $('#variableSelectorModal'),
            area: ['500px', '400px'],
            success: function () {
                // 监听搜索框输入
                $('#variableSearchKeyword').on('input', function () {
                    self.variableSearchKeyword = $(this).val();
                    self.renderVariableList();
                });

                // 监听变量点击
                $('#variableList').on('click', '.variable-item', function () {
                    var attrKey = $(this).data('key');
                    var variableValue = '${' + attrKey + '}';

                    if (self.currentElement) {
                        var element = self.currentElement;

                        // 根据元素类型和目标字段插入变量
                        switch (element.type) {
                            case 'text':
                                if (self.currentField === 'content') {
                                    element.content = (element.content || '') + variableValue;
                                }
                                break;
                            case 'image':
                                if (self.currentField === 'value') {
                                    element.value = variableValue;
                                    // 如果选择了变量，自动切换到变量模式
                                    element.sourceType = 'variable';
                                }
                                break;
                            case 'table':
                            case 'barcode':
                                if (self.currentField === 'value') {
                                    element.value = variableValue;
                                }
                                break;
                        }

                        // 更新属性面板
                        self.updatePropertyPanel();

                        // 重新渲染
                        self.renderElements();
                    }

                    layer.closeAll();
                });
            }
        });
    };

    /**
     * 渲染变量列表
     */
    PrintTemplateDesign.prototype.renderVariableList = function () {
        var self = this;
        var html = '';
        var keyword = self.variableSearchKeyword.toLowerCase();

        var filteredFields = self.businessFields;
        if (keyword) {
            filteredFields = self.businessFields.filter(function (field) {
                return field.name.toLowerCase().indexOf(keyword) > -1 ||
                    field.attrKey.toLowerCase().indexOf(keyword) > -1;
            });
        }

        $.each(filteredFields, function (i, field) {
            html += '<div class="variable-item" data-key="' + field.attrKey + '">' +
                '<div class="item-name">' + field.name + '</div>' +
                '<div class="item-key">' + field.attrKey + '</div>' +
                '</div>';
        });

        $('#variableList').html(html);
    };

    /**
     * 处理预览
     */
    PrintTemplateDesign.prototype.handlePreview = function () {
        var self = this;

        self.loading = true;

        // 先保存模板
        self.handleSave(false).then(function () {
            // 加载预览内容
            _openNewWindows({
                url: '../../tpl/printTemplate/preview.html?id=' + self.options.id,
                title: '模板预览',
                pageId: "previewTemplate",
                area: ['90vw', '90vh'],
                callBack: function (refreshCode) {
                }
            });
        }).catch(function () {
            self.loading = false;
            layer.msg('预览失败', { icon: 2 });
        });
    };

    /**
     * 处理保存
     */
    PrintTemplateDesign.prototype.handleSave = function (showTip) {
        var self = this;
        self.loading = true;

        // 确保打印设置的值有效
        if (!self.printSettings || !self.printSettings.paperSize) {
            self.printSettings = $.extend({}, self.printSettings || {}, {
                paperSize: 'A4_PAGE',
                orientation: 'portrait',
                width: 210,
                height: 297,
                margin: (self.printSettings && self.printSettings.margin) ? self.printSettings.margin : {
                    top: 10,
                    right: 10,
                    bottom: 10,
                    left: 10
                }
            });
        }

        return new Promise(function (resolve, reject) {
            // 确保打印设置中的值都有效
            var paperSize = self.printSettings.paperSize || 'A4_PAGE';
            var orientation = self.printSettings.orientation || 'portrait';
            var width = self.printSettings.width || 210;
            var height = self.printSettings.height || 297;
            var margin = self.printSettings.margin || { top: 10, right: 10, bottom: 10, left: 10 };

            var templateData = {
                id: self.options.id,
                configContent: JSON.stringify({
                    elements: self.elements.map(function (el) {
                        return $.extend({}, el, {
                            x: parseInt(el.x),
                            y: parseInt(el.y),
                            width: parseInt(el.width),
                            height: parseInt(el.height)
                        });
                    })
                }),
                width: paperSize === 'CUSTOM_PAGE' ? width : '',
                height: paperSize === 'CUSTOM_PAGE' ? height : '',
                paperSize: paperSize,
                orientation: orientation,
                margin: JSON.stringify(margin)
            };

            AjaxPostUtil.request({
                url: reqBasePath + 'editConfigContentById',
                params: templateData,
                type: 'json',
                method: 'POST',
                callback: function (json) {
                    if (showTip) {
                        layer.msg('保存成功', { icon: 1 });
                    }
                    self.loading = false;
                    resolve(json);
                },
                errorCallback: function (err) {
                    layer.msg('保存失败', { icon: 2 });
                    self.loading = false;
                    reject(err);
                }
            });
        });
    };

    /**
     * 显示表格列字段选择器
     */
    PrintTemplateDesign.prototype.showColumnFieldSelector = function (columnIndex) {
        var self = this;
        if (!self.currentElement || self.currentElement.type !== 'table') return;

        var element = self.currentElement;
        self.currentColumnIndex = columnIndex;

        // 解析数据源变量，获取子属性
        var dataSourceKey = '';
        if (element.value) {
            var match = element.value.match(/\$\{([^}]+)\}/);
            if (match && match[1]) {
                dataSourceKey = match[1];
            }
        }

        if (!dataSourceKey) {
            layer.msg('数据源变量格式不正确', { icon: 2 });
            return;
        }

        // 显示加载中提示
        var loadIndex = layer.load(1, { shade: [0.1, '#fff'] });

        // 获取父字段信息
        var parentField = self.businessFields.find(function (f) { return f.attrKey === dataSourceKey; });
        if (!parentField) {
            layer.close(loadIndex);
            layer.msg('找不到该数据源的字段信息', { icon: 2 });
            return;
        }

        // 调用接口获取子属性
        AjaxPostUtil.request({
            url: reqBasePath + 'queryChildAttrDefinitionList',
            params: {
                className: parentField.attrDefinitionCustom?.className,
                appId: parentField.attrDefinitionCustom?.appId,
                attrKey: parentField.attrKey
            },
            type: 'json',
            method: 'POST',
            callback: function (json) {
                layer.close(loadIndex);
                var childFields = json.rows || [];
                if (childFields.length === 0) {
                    layer.msg('当前数据源没有可选的子属性', { icon: 0 });
                    return;
                }

                // 保存子字段列表到实例中
                self.childFields = childFields;

                // 生成字段选择器HTML
                var html = '<div class="field-selector" style="padding:10px;">' +
                    '<div class="search-box" style="margin-bottom:10px;">' +
                    '<input type="text" id="fieldSearchKeyword" placeholder="搜索字段" class="layui-input">' +
                    '</div>' +
                    '<div class="field-list" style="max-height:300px;overflow-y:auto;">';

                childFields.forEach(function (field) {
                    html += '<div class="field-item" style="padding:8px;border-bottom:1px solid #f0f0f0;cursor:pointer;display:flex;justify-content:space-between;" data-key="' + field.attrKey + '">' +
                        '<div class="field-info">' +
                        '<div class="field-name" style="font-weight:500;">' + field.name + '</div>' +
                        '<div class="field-key" style="color:#999;font-size:12px;">' + field.attrKey + '</div>' +
                        '</div>' +
                        '<div class="field-type" style="color:#888;">' + (field.attrType || '未知') + '</div>' +
                        '</div>';
                });

                html += '</div></div>';

                // 显示字段选择器弹窗
                layer.open({
                    type: 1,
                    title: '选择字段',
                    content: html,
                    area: ['500px', '400px'],
                    success: function () {
                        // 监听搜索框输入
                        $('#fieldSearchKeyword').on('input', function () {
                            var keyword = $(this).val().toLowerCase().trim();
                            $('.field-item').each(function () {
                                var fieldName = $(this).find('.field-name').text().toLowerCase();
                                var fieldKey = $(this).find('.field-key').text().toLowerCase();
                                if (fieldName.indexOf(keyword) > -1 || fieldKey.indexOf(keyword) > -1) {
                                    $(this).show();
                                } else {
                                    $(this).hide();
                                }
                            });
                        });

                        // 监听字段点击
                        $('.field-item').on('click', function () {
                            var attrKey = $(this).data('key');
                            var variableValue = '${' + attrKey + '}';

                            // 设置列字段值
                            if (element.columns && element.columns[self.currentColumnIndex]) {
                                var column = element.columns[self.currentColumnIndex];
                                column.field = variableValue;

                                // 如果标题为空，使用字段名作为标题
                                if (!column.title) {
                                    var fieldName = $(this).find('.field-name').text();
                                    column.title = fieldName;
                                }
                            }

                            // 更新属性面板
                            self.updatePropertyPanel();

                            // 关闭弹窗
                            layer.closeAll();
                        });
                    }
                });
            },
            errorCallback: function () {
                layer.close(loadIndex);
                layer.msg('获取子属性失败', { icon: 2 });
            }
        });
    };

    /**
     * 处理表格列属性变化
     */
    PrintTemplateDesign.prototype.handleColumnPropertyChange = function (name, value) {
        var self = this;
        if (!self.currentElement || self.currentElement.type !== 'table') return;

        var element = self.currentElement;
        if (!element.columns || !Array.isArray(element.columns)) return;

        // 解析属性名，格式如：columnTitle_0, columnWidth_1, columnAlign_2 等
        var parts = name.split('_');
        if (parts.length !== 2) return;

        var propertyName = parts[0];
        var columnIndex = parseInt(parts[1]);

        // 确认列索引有效
        if (isNaN(columnIndex) || columnIndex < 0 || columnIndex >= element.columns.length) return;

        var column = element.columns[columnIndex];

        // 根据属性名前缀确定要设置的列属性
        switch (propertyName) {
            case 'columnTitle':
                column.title = value;
                break;
            case 'columnField':
                column.field = value;
                break;
            case 'columnWidth':
                column.width = value;
                break;
            case 'columnAlign':
                column.align = value;
                break;
            case 'columnFontSize':
                column.fontSize = value;
                break;
            case 'columnWrap':
                column.wrap = value;
                break;
        }

        // 重新渲染
        self.renderElements();
    };

    const id = GetUrlParam('id');
    const businessClassName = GetUrlParam('businessClassName') || '';
    const appId = GetUrlParam('appId') || '';
    // 创建实例
    window.printTemplateDesign = new PrintTemplateDesign({
        id: id,
        businessClassName: businessClassName,
        appId: appId
    });
});
